大家好,又见面了,我是你们的朋友全栈君。
今天学习使用了HttpClient4.2向服务端发送上传文件的post请求,由于服务器端采用MultipartFile形式接收,查询资料后决定使用HttpClient4.2实现,以下是实现代码(仅作测试使用):
public void testtaskPost()throws Exception{
HttpClient httpclient = new DefaultHttpClient();
try {
//新建一个httpclient Post 请求
HttpPost httppost = new
HttpPost("http://127.0.0.1:8889/taskmanagement/task");
//由于只是测试使用 这里的路径对应本地文件的物理路径
FileBody bin = new FileBody(new File("E://2017//1.doc"));
File myfile = new File("E://2017//1.doc");
long size = myfile.length();
//向MultipartEntity添加必要的数据
StringBody comment = new StringBody("1.doc",
Charset.forName("UTF-8"));
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file",bin);//file为请求后台的Fileupload参数
reqEntity.addPart("filename",comment);//请求后台Fileupload的参数
httppost.setEntity(reqEntity);
//这里是后台接收文件的接口需要的参数,根据接口文档需要放在http请求的请求头
String taskid ="919894d9-ea5a-4f6a-8edd-b14ef3b6f104";
httppost.setHeader("task-id",taskid);
String fileid = UUID.randomUUID().toString();
httppost.setHeader("file-id",fileid);
httppost.setHeader("file-name","1.doc");
httppost.setHeader("file-size",String.valueOf(size));
httppost.setHeader("total", String.valueOf(1));
httppost.setHeader("index",String.valueOf(1));
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK){
System.out.println("服务器正常响应.....");
HttpEntity resEntity = response.getEntity();
System.out.println(
//httpclient自带的工具类读取返回数据
EntityUtils.toString(resEntity));
System.out.println( resEntity.getContent());
EntityUtils.consume( resEntity);
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.getConnectionManager().shutdown();
} catch (Exception ignore) {
}
}
}
此段代码所需依赖包下载地址(免积分的):http://download.csdn.net/detail/coding13/9772027
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/163265.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...