post请求上传文件


1依赖

org.apache.httpcomponents

httpclient

4.5.2

org.apache.httpcomponents

httpmime

4.5.2

2.方法

public static JSONObject doFormDataPost(File file, String sURL) throws IOException {

HttpClient context = new DefaultHttpClient();
HttpPost post = new HttpPost(sURL);
post.setHeader("user","x");
post.setHeader("key","x");

String fileName = "{'filename':'onetime.docx'}";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("files", file);//添加文件
builder.addTextBody("code", "29002"); //添加文本类型参数
builder.addTextBody("content", fileName); //添加文本类型参数

post.setEntity(builder.build());
HttpResponse response = context.execute(post);

HttpEntity responseEntity = response.getEntity();
String resEntity= EntityUtils.toString(responseEntity, "UTF-8");
JSONObject jsonObject = JSONObject.parseObject(resEntity);

return jsonObject;
}

3调用

doFormDataPost(new File("D:\\tmp\\发送文件.docx"),"http://xxxx/api/xxxx");

相关