httpPost发送json或xml参数的请求

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HttpClientUtil {
//josn参数发送post请示
private String doPostJson(String url,Map<String,String> headers,String jsonStr) throws Exception{
//创建连接
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
//设置json的请求头
post.setHeader(“Accept”,“application/json”);
post.setHeader(“Content-Type”,“application/json”);
for (Map.Entry<String,String> entry : headers.entrySet()){
post.setHeader(entry.getKey(),entry.getValue());
}
//设置json的参数
StringEntity entry = new StringEntity(jsonStr,“UTF-8”);
entry.setContentType(“application/json”);
post.setEntity(entry);
//发请示
HttpResponse response = httpClient.execute(post);
return EntityUtils.toString(response.getEntity());
}
//xml发送post请示
private String doPostXml(String url,Map<String,String> headerMap,String xmlString) throws Exception{
HttpClient httpClient = HttpClientBuilder.create().build();
StringEntity stringEntity = new StringEntity(getXmlString(headerMap,xmlString),“GBK”);
stringEntity.setContentEncoding(“GBK”);
stringEntity.setContentType(“text/xml”);
//创建连接
HttpPost post = new HttpPost(url);
post.setEntity(stringEntity);
HttpResponse response = httpClient.execute(post);
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity,“GBK”);
return result;
}
//拼接xml参数
private static String getXmlString(Map<String,String> headerMap,String xmlString){
StringBuffer xml = new StringBuffer();
xml.append("<?xml version=\"1.0\" encoding=\"GBK\"?>");
xml.append("<Packet type=“REQUEST” version=“1.0”>");
xml.append(getHeader(headerMap));
xml.append(xmlString);
xml.append("");
return xml.toString();
}
//拼接header
private static String getHeader(Map<String,String> headerMap){
StringBuffer header = new StringBuffer();
header.append("");
Set<Map.Entry<String, String>> entry = headerMap.entrySet();
Iterator<Map.Entry<String, String>> iterator = entry.iterator();
if (iterator.hasNext()){
Map.Entry<String,String> entryNext = iterator.next();
header.append("<"+entryNext.getKey()+">"+entryNext.getValue()+"<"+entryNext.getKey()+">");
}
header.append("");
return header.toString();
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值