简体   繁体   中英

How can I attach name-value pairs to a MultiPart POST request?

This example works great for one or the other, but not both:

public void postData() {  
    //http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/
    File f = new File(filename);
    try {
             HttpClient client = new DefaultHttpClient();  
             String postURL = "http://url.com/script.php";


             HttpPost post = new HttpPost(postURL); 
    //         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
      //       nameValuePairs.add(new BasicNameValuePair("project", projectName));  
        //     nameValuePairs.add(new BasicNameValuePair("name", imageName));  
          //   post.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

             FileBody bin = new FileBody(f);
             MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
             reqEntity.addPart("file", bin);

             post.setEntity(reqEntity); 

             HttpResponse response = client.execute(post);  
             HttpEntity resEntity = response.getEntity();  
             if (resEntity != null) {    
                       Log.i("RESPONSE",EntityUtils.toString(resEntity));
                 }
    } catch (Exception e) {
        e.printStackTrace();
    }


}

It seems as if when I call setEntity() , the previous entity is overwritten -- so I can either have name value pairs, or file data, but not both. Do you know how to integrate them so I can use URL parameters in my upload? Simply appending them to the POST URL does not work.

I also tried

  post.addHeader("project", projectName);
  post.addHeader("name", imageName);                 

but that didn't seem to work either.

Thanks.

This seems to do the trick:

             reqEntity.addPart("project", new StringBody(projectName));
             reqEntity.addPart("name", new StringBody(imageName));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM