java - 使用 Android 通过 HttpRequest 发送简单的 POST

标签 java android http-post httprequest

我希望我的应用程序通过查询字符串将两个字符串发送到一个 php 文件,该文件将把它们作为 POST 变量处理。

到目前为止我有这段代码

public void postData() {    
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("www.mywebsite.com/my_phpfile.php?var1=20&var2=31");

    try {

    HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

我认为这是一个容易解决的问题,但这是我的第一个 Android 应用程序,我将不胜感激所有帮助。

最佳答案

使用 nameValuePairs 在 POST 请求中传递数据。

像这样尝试:

public void postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php");

    try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "123"));
        nameValuePairs.add(new BasicNameValuePair("string", "Hey"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // Catch Protocol Exception
    } catch (IOException e) {
        // Catch IOException
    }
} 

关于java - 使用 Android 通过 HttpRequest 发送简单的 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16256717/

相关文章:

java - 更改 Firebase Recycler Adapter 中的项目位置

android - 从 firebase 检索复杂的嵌套数据

angularjs - 在 Angular 2 中发出 http POST 请求

java - 如何通过 Apache HttpClient 执行以 xml 数据作为查询参数的 url?

java - 使用 "else"会加速代码的执行吗?

Android:<3.0 上不显示 CheckBoxPreference 图标?

每帧调用的Java函数

json - 如何在Laravel 5中获取原始json请求有效载荷?

java - 图像处理 - 曝光对图像的影响

java分组正则表达式无法匹配字符串+文本