package com.http; import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test; public class HttpClientUtil { @Test
public void testHttp() {
//创建HttpClient对象
HttpClient client = new DefaultHttpClient();
//构建POST请求 请求地址请更换为自己的。
//1)
HttpPost post = new HttpPost("XX");
File file=new File("C:\\Users\\admin\\Desktop\\xidada.jpg");
FileBody fileBody=new FileBody(file);
try {
StringBody name = new StringBody("xidada.jpg");
MultipartEntity reqEntity = new MultipartEntity();
StringBody bucketId = new StringBody("402880bd66a545e90166a545f3700000");
reqEntity.addPart("bucketId", bucketId);//对应接口端的参数名称
reqEntity.addPart("name", name);
reqEntity.addPart("file", fileBody);//file1为请求后台的File upload;属性
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK){ System.out.println("服务器正常响应....."); HttpEntity resEntity = response.getEntity(); System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据
System.out.println(resEntity.getContent());
EntityUtils.consume(resEntity);
}
}catch (UnsupportedEncodingException e) { e.printStackTrace();
} catch (ClientProtocolException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
} }
}
httpclient-4.2.2.jar
httpcore-4.2.2.jar
httpmime-4.2.2.jar