项目开发中遇到一个需求 需要推送给第三方一个参数名为"params"文本类型的form-data参数的post请求
在使用httpClient一般的post请求大多都是为json的参数 下面给大家介绍一下 如果传入带有参数的form-data的请求
废话不多说 直接上代码
这里我是封装了一个httpUtils 以下为方法
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import java.nio.charset.Charset;
import java.util.*;
@Slf4j
public class HttpUtils {
//JSON方式的调用 (这里入参我是选用了Map类型 然后通过JSON转了一下,非常人性化)
public static Map post(String url, Map body) {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json");
StringEntity entity = new StringEntity(Objects.requireNonNull(JSON.toJSONString(body)), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
return doExecute(httpPost);
}
//form-data类型 这个的入参因为我的需求是JSON数据 所以我这边入参选用了LIST<MAP>
public static Map postTst(String url, List<Map> body){
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//注意这里 首先我这边没有设置http请求头 如果不加contenType的话 会出现参数乱码
ContentType contentType = ContentType.create("text/plain", "UTF-8");
//这里依然是使用addTextBoby的方式带有contentType的方法
builder.addTextBody("params",JSON.toJSONString(body),contentType);
httpPost.setEntity(builder.build());
return doExecute(httpPost);
}
private static Map doExecute(HttpUriRequest request) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse;
httpResponse = httpClient.execute(request);
int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
if (httpResponseCode != 200) {
log.error("doExecute. httpResponseCode={}, request={}", httpResponseCode, request);
}
String resultString = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
return JSON.parseObject(resultString, Map.class);
} catch (Exception e) {
log.error("doExecute error:", e);
return null;
}
}
private static String doExecuteTest(HttpUriRequest request) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse;
httpResponse = httpClient.execute(request);
int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
if (httpResponseCode != 200) {
log.error("doExecute. httpResponseCode={}, request={}", httpResponseCode, request);
}
return EntityUtils.toString(httpResponse.getEntity(), "utf-8");
} catch (Exception e) {
log.error("doExecute error:", e);
return null;
}
}
public static void main(String[] args) {
List<Map> list =new ArrayList<>();
Map map = new HashMap();
map.put("name","赖勇强");
map.put("idcard","362532199308071714");
map.put("lanCode","360000");
map.put("countyCode","1");
map.put("bizType","8");
map.put("targetUrl","");
map.put("pushTemplateJson","{\"bizcode\":\"xkslwk\",\"jfyhxm\":\"赖勇强测试\",\"jfsj\":\"2020-12-21\",\"jfje\":\"100.2\"}");
list.add(map);
Map post = postTst("https://ganfutong.jiangxi.gov.cn/dztxcs/interfaces/dztxgeneral/dztxGeneralPushData.do", list);
System.out.println("post--->"+post);
}
}
至此就调用成功了,乱码问题也解决了。
百度上有很多方式都可以去实现添加form-data格式参数这里我认为MultipartEntityBuilder类还是比较健壮的
还有乱码问题 网上也有很多解决办法 例如:
这个他是选用了 springBoby转换了一下 使用addPart去做处理
我觉得首先addTextBody这个方法 已经给出了
可以指定contentType的方式去调用这里就可以直接指定格式 比较简便快捷 非常淫性化