【问题标题】:Sending simple POST by HttpRequest with Android使用 Android 通过 HttpRequest 发送简单的 POST
【发布时间】:2013-04-27 20:46:30
【问题描述】:

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

到目前为止我有这个代码

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 应用程序,我会感谢所有帮助。

【问题讨论】:

    标签: java android http-post httprequest


    【解决方案1】:

    使用 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
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 2015-07-24
      相关资源
      最近更新 更多