HttpClient发送post和get请求方法模板

    项目中经常会用到利用http协议向指定接口发起post(传送数据)或get(获取数据)请求来处理业务,以下整理了http协议请求常用到的两种请求方法,可作为通用工具类使用:

public class HttpUtils {

/**
* post请求
*/
public static JSONObject doPost(String url, Map<String, String> params) {
JSONObject json = null;
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间30秒

RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();

httpPost.setConfig(requestConfig);

// 设置请求头参数
httpPost.setHeader("dealer-id", "12345678");//代码
httpPost.setHeader("request-id", IdGen.uuid());// request的 id
// 设置参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String value = String.valueOf(params.get(name));
nvps.add(new BasicNameValuePair(name, value));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
System.out.println("doPost请求url:" + httpPost.toString());
// 执行post请求
CloseableHttpResponse response = httpClient.execute(httpPost);
String respStr = EntityUtils.toString(response.getEntity(), "UTF-8");
json = JSON.parseObject(respStr);
response.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
/**
* get请求
*/
public static JSONObject doGet(String url, Map<String, String> params) {
JSONObject json = null;
try {
// 设置参数
Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
StringBuilder urlBuffer = new StringBuilder();
urlBuffer.append(url + "?");
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
Object key = entry.getKey();
urlBuffer.append(key);
urlBuffer.append('=');
String value = URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");//参数加密
urlBuffer.append(value);
if (it.hasNext()) {
urlBuffer.append("&");
}
}
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(urlBuffer.toString());
System.out.println("doGet请求url:" + urlBuffer.toString());
// 设置请求和传输超时时间30秒

RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();

httpGet.setConfig(requestConfig);

// 设置请求头参数
httpGet.setHeader("dealer-id", "12345678");//代码
httpGet.setHeader("request-id", IdGen.uuid());// request的 id
// 执行get请求
CloseableHttpResponse response = httpClient.execute(httpGet);
String respStr = EntityUtils.toString(response.getEntity(), "UTF-8");
json = JSON.parseObject(respStr);
response.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值