java post请求raw_httpClient中post请求并传送form-data数据(同样适用于Raw的application-json格式)...

httpClient模仿Postman的form-data格式

d295e7ccb6dda0308aac753081cc985e.png

话不多说,直接上代码

依赖包:

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值