package cn.com.wind.utils;
import cn.com.wind.exception.TranspondException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* @Author qymeng
* @Date 2021/10/25
* @Description 接口转发的工具类
*/
@Slf4j
public class TranspondUtils {
/**
* POST请求
*
* @param json 请求的json体
* @param url 请求的url地址
*/
public static String doPost(String json, String url) {
HttpClient httpClient = new HttpClient();
// 设置http连接主机服务超时时间
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(35000);
PostMethod postMethod = new PostMethod(url);
// 设置post请求超时
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
// 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
String result = null;
try {
RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8");
//请求头信息
postMethod.setRequestHeader("Content-Type", "application/json");
postMethod.setRequestEntity(entity);
httpClient.executeMethod(postMethod);
if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
// 获取响应输入流
InputStream inStream = postMethod.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8));
StringBuilder strber = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
strber.append(line).append("\n");
inStream.close();
result = strber.toString();
} else {
throw new TranspondException("请求服务端失败,状态码不为200");
}
} catch (IOException e) {
throw new TranspondException("请求服务端失败,地址为:" + url);
} catch (IllegalStateException e) {
throw new TranspondException("url地址不正确,该地址为:" + url);
} catch (Exception e) {
throw new TranspondException("其他异常");
}
return result;
}
public static String doPost(JSONObject json, String url) {
String s = JSON.toJSONString(json);
return doPost(s, url);
}
public static String doPost(Object json, String url) {
String s = JSON.toJSONString(json);
return doPost(s, url);
}
/**
* GET请求
*
* @param url 请求的url地址
*/
public static String doGet(String url) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
// 通过址默认配置创建一个httpClient实例
httpClient = HttpClients.createDefault();
// 创建httpGet远程连接实例
HttpGet httpGet = new HttpGet(url);
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 请求超时时间
.setSocketTimeout(60000)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
httpGet.setConfig(requestConfig);
// 执行get请求得到返回对象
response = httpClient.execute(httpGet);
// 通过返回对象获取返回数据
HttpEntity entity = response.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
result = EntityUtils.toString(entity);
// log.info("请求服务器成功");
} catch (IOException e) {
throw new TranspondException("GET请求异常, URL为:" + url);
} finally {
// 关闭资源
if (null != response) {
try {
response.close();
} catch (IOException e) {
throw new TranspondException("关闭CloseableHttpResponse时出现异常, URL为:" + url);
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
throw new TranspondException("关闭CloseableHttpClient时出现异常, URL为:" + url);
}
}
}
return result;
}
public static JSONObject doGetJson(String url) {
return JSONObject.parseObject(doGet(url));
}
}