关闭

android HttpClient 上传图片

标签: androidfileexceptionnullimportstring
2031人阅读 评论(1) 收藏 举报
  1. import java.io.File;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.HttpVersion;
  5. import org.apache.http.client.HttpClient;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.entity.FileEntity;
  8. import org.apache.http.impl.client.DefaultHttpClient;
  9. import org.apache.http.params.CoreProtocolPNames;
  10. import org.apache.http.util.EntityUtils;


  11. public class PostFile {
  12.   public static void main(String[] args) throws Exception {
  13.     HttpClient httpclient = new DefaultHttpClient();
  14.     httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

  15.     HttpPost httppost = new HttpPost("http://localhost:9002/upload.php");
  16.     File file = new File("c:/TRASH/zaba_1.jpg");

  17.     FileEntity reqEntity = new FileEntity(file, "binary/octet-stream");

  18.     httppost.setEntity(reqEntity);
  19.     reqEntity.setContentType("binary/octet-stream");
  20.     System.out.println("executing request " + httppost.getRequestLine());
  21.     HttpResponse response = httpclient.execute(httppost);
  22.     HttpEntity resEntity = response.getEntity();

  23.     System.out.println(response.getStatusLine());
  24.     if (resEntity != null) {
  25.       System.out.println(EntityUtils.toString(resEntity));
  26.     }
  27.     if (resEntity != null) {
  28.       resEntity.consumeContent();
  29.     }

  30.     httpclient.getConnectionManager().shutdown();
  31.   }
  32. }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:285058次
    • 积分:3270
    • 等级:
    • 排名:第10794名
    • 原创:4篇
    • 转载:264篇
    • 译文:1篇
    • 评论:22条
    最新评论