httpclient请求有file类型
1、接口参数类型:File和其他普通类型
2、遇到的问题:开始接口请求一直不通过,提示没有传参,主要问题
请求头中传了错误的Content-Type没有删除**
httpGet.setHeader(“Content-Type”, “application/json”);
有file类,需要使用MULTIPART_FORM_DATA
builder.addBinaryBody("file",inputStream, ContentType.MULTIPART_FORM_DATA, fileName);
for (Map.Entry<String, String> entrySet : param.entrySet()) {
String key = entrySet.getKey();
String value = entrySet.getValue();
StringBody body = new StringBody(value, ContentType.TEXT_PLAIN);
builder.addPart(key, body);
}
关于Content-Type说明
https://www.cnblogs.com/52fhy/p/5436673.html
方法一:File和其他普通类型参数都可以传入body中
public static String doFilePost(String url, Map<String, String> param, String token,File file) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url );
httpPost.setHeader("TT", token);
String fileName = file.getName();
FileInputStream inputStream = new FileInputStream(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file",inputStream, ContentType.MULTIPART_FORM_DATA, fileName);
for (Map.Entry<String, String> entrySet : param.entrySet()) {
String key = entrySet.getKey();
String value = entrySet.getValue();
StringBody body = new StringBody(value, ContentType.TEXT_PLAIN);
builder.addPart(key, body);
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String getentity = EntityUtils.toString(response.getEntity());
JSONObject responseResult = JSONObject.parseObject(getentity);
System.out.println(("请求响应结果:" + responseResult));
String result = "";
if (responseResult.get("code").equals("200")) {
result = responseResult.getString("data");
// System.out.println("打印data:" + result);
}
else{
String msg = responseResult.getString("msg");
System.out.println("接口报错:" + msg);
}
return result;
}
方法二:普通参数也可以直接拼接在url后面
public static String doFilePost(String url, String param, String token,File file) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url +"?"+param);
httpPost.setHeader("TT", token);
String fileName = file.getName();
FileInputStream inputStream = new FileInputStream(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file",inputStream, ContentType.MULTIPART_FORM_DATA, fileName);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String getentity = EntityUtils.toString(response.getEntity());
JSONObject responseResult = JSONObject.parseObject(getentity);
System.out.println(("请求响应结果:" + responseResult));
String result = "";
if (responseResult.get("code").equals("200")) {
result = responseResult.getString("data");
// System.out.println("打印data:" + result);
}
else{
String msg = responseResult.getString("msg");
System.out.println("接口报错:" + msg);
}
return result;
}