0
点赞
收藏
分享

微信扫一扫

Android 通过HTTP POST&…

SPEIKE 2023-04-30 阅读 85


HttpComponents libraries

. Download the latest HttpClient (currently 4.0.1

) binary with dependencies package and copy  apache-mime4j-0.6.jar

and  httpmime-4.0.1.jar

to your project and add them to your Java build path.


You will need to add the following imports to your class.

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

Now you can create a MultipartEntity to attach an image to your POST request. The following code shows an example of how to do this:



1. public void post(String url, List nameValuePairs) {  
2.    HttpClient httpClient = new DefaultHttpClient();  
3.    HttpContext localContext = new BasicHttpContext();  
4.    HttpPost httpPost = new HttpPost(url);  
5.  
6.    try {  
7.        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
8.  
9.        for(int index=0; index < nameValuePairs.size(); index++) {  
10.            if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {  
11.                // If the key equals to "image", we use FileBody to transfer the data   
12.                entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));  
13.            } else {  
14.                // Normal string data   
15.                entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));  
16.            }  
17.        }  
18.  
19.        httpPost.setEntity(entity);  
20.  
21.        HttpResponse response = httpClient.execute(httpPost, localContext);  
22.    } catch (IOException e) {  
23.        e.printStackTrace();  
24.    }  
25. }

举报

相关推荐

0 条评论