java httpclient 工具_java httpclient工具类

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

import org.apache.http.HttpEntity;

import org.apache.http.HttpStatus;

import org.apache.http.NameValuePair;

import org.apache.http.ParseException;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

import java.io.IOException;

import java.util.*;/**

* HttpClient4.3工具类*/@Slf4jpublic classHttpClientUtils {private static RequestConfig requestConfig = null;private static String charset = "utf-8";public static voidmain(String[] args) {

JSONObject tt= newJSONObject();

tt.put("aaa", "4444");

Map mm= newHashMap();

mm.put("aaa", "555");//System.out.println("result:" + httpPost("http://127.0.0.1:8761/hi1", tt));//System.out.println("result:" + httpPost("http://127.0.0.1:8761/hi1", mm));//System.out.println("result:" + httpPost("http://127.0.0.1:8761/hi1", JSON.toJSONString(mm)));

System.out.println("result:" + httpPostForm("http://127.0.0.1:8761/hi2", mm));

}static{//设置请求和传输超时时间

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

}/**

* @param url

* @param obj 1. json字符串 2. map 3.JSONObject

* @return JSONObject*/

public staticJSONObject httpPost(String url, Object obj) {//post请求返回结果

CloseableHttpClient httpClient =HttpClients.createDefault();

JSONObject jsonResult= null;

HttpPost httpPost= newHttpPost(url);//设置请求和传输超时时间

httpPost.setConfig(requestConfig);try{if (null !=obj) {

StringEntity entity= null;if(obj instanceof String) {

entity= newStringEntity(obj.toString(), charset);

}else{

entity= newStringEntity(JSON.toJSONString(obj), charset);

}

entity.setContentEncoding(charset);

entity.setContentType("application/json");

httpPost.setEntity(entity);

}

log.debug("{} - {}", url, obj);

CloseableHttpResponse response=httpClient.execute(httpPost);returnconvertResponse(response);

}catch(Exception e) {

log.error("error HttpClientUtils {} - {} - {}" +url, obj, e);

}finally{

httpPost.releaseConnection();

}returnjsonResult;

}/**

* post请求传输String参数 例如:name=Jack&sex=1&type=2

* Content-type:application/x-www-form-urlencoded

*

* @param url url地址

* @param

* @return*/

public static JSONObject httpPostForm(String url, Map params) {//post请求返回结果

CloseableHttpClient httpClient =HttpClients.createDefault();

JSONObject jsonResult= null;

HttpPost httpPost= newHttpPost(url);

httpPost.setConfig(requestConfig);try{if (null != params) {//组织请求参数

List paramList = new ArrayList();if (params != null && params.size() > 0) {

Set keySet = params.keySet();for(String key : keySet) {

paramList.add(new BasicNameValuePair(key, params.get(key)));

}

}

httpPost.setEntity(newUrlEncodedFormEntity(paramList, charset));

}

CloseableHttpResponse response=httpClient.execute(httpPost);returnconvertResponse(response);

}catch(IOException e) {

log.error("post请求提交失败:" +url, e);

}finally{

httpPost.releaseConnection();

}returnjsonResult;

}/**

* 发送get请求

*

* @param url 路径

* @return*/

public staticJSONObject httpGet(String url) {//get请求返回结果

JSONObject jsonResult = null;

CloseableHttpClient client=HttpClients.createDefault();//发送get请求

HttpGet request = newHttpGet(url);

request.setConfig(requestConfig);try{

CloseableHttpResponse response=client.execute(request);

convertResponse(response);

}catch(Exception e) {

log.error("get请求提交失败:" +url, e);

}finally{

request.releaseConnection();

}returnjsonResult;

}private staticJSONObject convertResponse(CloseableHttpResponse response) throws IOException, ParseException {//请求发送成功,并得到响应

if (response.getStatusLine().getStatusCode() ==HttpStatus.SC_OK) {//读取服务器返回过来的json字符串数据

HttpEntity entity =response.getEntity();

String strResult= EntityUtils.toString(entity, "utf-8");//把json字符串转换成json对象

returnJSONObject.parseObject(strResult);

}else{

log.error("{}", response);

}return null;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值