Android 通过HTTP POST&…

Sending images can be done using the  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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值