httpClient模仿Postman的form-data格式
话不多说,直接上代码
依赖包:
org.apache.httpcomponents
httpcore
org.apache.httpcomponents
httpclient
org.apache.httpcomponents
httpmime
适用于post请求并传送form-data数据(同样适用于Raw类型的application-json格式)
public static String postParams(String url, Map params) {
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
//创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
HttpPost post = new HttpPost(url);
CloseableHttpResponse res = null;
try {
List nvps = new ArrayList();
Set keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
res = client.execute(post);
HttpEntity entity = res.getEntity();
return EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
res.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
再来个head传参版:
public static String postMethod(String url, String params, String contentType, String head) {//创建HttpClientBuilder
HttpClientBuilder httpClientBuilder =HttpClientBuilder.create();//HttpClient
CloseableHttpClient client =httpClientBuilder.build();
client=(CloseableHttpClient) wrapClient(client);
HttpPost post= newHttpPost(url);
CloseableHttpResponse res= null;try{
StringEntity s= new StringEntity(params, "UTF-8");if(StringUtils.isBlank(contentType)) {
s.setContentType("application/json");
}
s.setContentType(contentType);
s.setContentEncoding("utf-8");
post.setEntity(s);if(StringUtils.isNotBlank(head)) {
post.addHeader("Authorization", head); //依据你自己的head传参进行改造
}
res=client.execute(post);
HttpEntity entity=res.getEntity();return EntityUtils.toString(entity, "utf-8");
}catch(Exception e) {
e.printStackTrace();
}finally{try{
res.close();
client.close();
}catch(IOException e) {
e.printStackTrace();
}
}return "";
}
业务层代码调用示例:
Map params = new HashMap<>();params.put("参数1",xxx.toString());params.put("参数2",xxx.toString());
String result= postParams(你的url,params);