如何在android http POST中添加参数?

时间:2010-07-20 09:56:35

标签: android

朋友,

我正在尝试使用以下教程将文件上传到php服务器 http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html

我不知道如何添加

等参数
  

用户id = “12312”;的sessionid = “234”

在其中。

任何人都指导我如何实现这个目标?

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:66)

如何制作http POST并添加参数。

如何添加参数?你必须有类似的东西。

// Add your data  
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
nameValuePairs.add(new BasicNameValuePair("userid", "12312"));  
nameValuePairs.add(new BasicNameValuePair("sessionid", "234"));  
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

这是一个完整的方法:

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/myexample.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "stackoverflow.com is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

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