android HttpClient 上传图片

  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. }

你可能感兴趣的:(android,exception,String,File,null,import)