/**
* okhttp工具
*
* @author tangjiabin
* @date 2018/5/24 17:01
*/
@Slf4j
public class OkHttpUtil {
private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
private static final OkHttpClient CLIENT = new OkHttpClient();
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final String HTTPS = "https";
/**
* 每行大小
*/
private static final int STREAM_READ_LENGTH = 1024;
/**
* @return String
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @Description: get请求
* @author tangjiabin
*/
public static String getOkHttp(String url) throws Exception {
Request request = new Request.Builder().url(url).build();
Response response;
String retStr;
try {
turnSsl();
response = CLIENT.newCall(request).execute();
if (response.isSuccessful()) {
retStr = response.body().string();
} else {
retStr = response.message();
}
} catch (Exception e) {
logger.error("【http工具类错误】", e);
throw new Exception(e);
}
return retStr;
}
/**
* get调用返回有状态的数据
*
* @param url
* @return com.iboxpay.base.common.model.Result<java.lang.String>
* @throws
* @author tangjiabin
* @date 2018/5/24 17:36
*/
public static Result<String> getOkHttpWithResult(String url){
Request request = new Request.Builder().url(url).build();
Response response;
String retStr;
Result<String> resp = ResultMessageUtil.dataResult();
try {
turnSsl();
response = CLIENT.newCall(request).execute();
if (response.isSuccessful()) {
retStr = response.body().string();
resp = ResultMessageUtil.successDataResult(retStr);
} else {
retStr = response.message();
resp = ResultMessageUtil.failDataResult("失败", retStr);
}
} catch (Exception e) {
logger.error("【http工具类错误】", e);
}
return resp;
}
/**
* 设置Post请求
* @param url
* @param json
* @return : com.squareup.okhttp.Response
* @author : tangjiabin
* @date 2018/7/3 21:46
*/
public static Response setPostOkHttp(String url, String json) throws IOException {
// 申明给服务端传递一个json串
// 创建一个OkHttpClient对象
// 创建一个RequestBody(参数1:数据类型 参数2传递的json串)
RequestBody requestBody = RequestBody.create(JSON, json);
// 创建一个请求对象
Request request = new Request.Builder().url(url).post(requestBody).build();
return CLIENT.newCall(request).execute();
}
/**
* @return String
* @Description: POST请求
* @author tangjiabin
*/
public static String postOkHttp(String url, String json) throws IOException {
String retStr;
try {
Response response = setPostOkHttp(url,json);
// 判断请求是否成功
if (response.isSuccessful()) {
retStr = response.body().string();
} else {
retStr = response.code() + "@_@" + response.message();
}
} catch (IOException e) {
e.printStackTrace();
logger.error("【post请求异常】", e);
throw new IOException(e);
}
return retStr;
}
/**
* 发送getHttp请求
* @param url
* @return : com.iboxpay.base.common.model.Result<java.lang.String>
* @author : tangjiabin
* @date 2018/7/3 22:51
*/
public static Result<String> sendGetOkHttp(String url){
return getOkHttpWithResult(url);
}
/**
* 发送postHttp请求
* @param url
* @param json
* @return : com.iboxpay.base.common.model.Result<java.lang.String>
* @author : tangjiabin
* @date 2018/7/3 22:45
*/
public static Result<String> sendPostOkHttp(String url, String json){
Result<String> result = ResultMessageUtil.dataResult();
try {
Response response = setPostOkHttp(url,json);
// 判断请求是否成功
if (response.isSuccessful()) {
String retStr = response.body().string();
result.setData(retStr);
ResultMessageUtil.successResult(result);
} else {
ResultMessageUtil.failResult(result,String.valueOf(response.code()),response.message());
}
} catch (IOException e) {
logger.error("【post请求异常】", e);
ResultMessageUtil.failResult(result,"0000","post请求异常");
}
return result;
}
/**
* post请求调用返回文件
*
* @param url
* @param json
* @return : byte[]
* @author : tangjiabin
* @date 2018/7/3 21:40
*/
public static Result<byte[]> sendPostOkHttpFile(String url, String json){
Result<byte[]> result = ResultMessageUtil.dataResult();
InputStream inputStream = null;
try {
Response response = setPostOkHttp(url,json);
// 判断请求是否成功
if (!response.isSuccessful()) {
log.error("【调用HTTP请求异常】 code:{},message:{}", response.code(), response.message());
ResultMessageUtil.failResult(result,"0000","HTTP请求异常");
}
inputStream = response.body().byteStream();
result.setData(inputToByte(inputStream));
ResultMessageUtil.successResult(result);
} catch (IOException e) {
logger.error("【post请求异常】", e);
ResultMessageUtil.failResult(result,"0000","post请求异常");
} finally {
try {
inputStream.close();
} catch (IOException e) {
log.error("【关闭流异常】");
}
}
return result;
}
/**
* inputStream转换成byte数组
*
* @param inputStream
* @return : byte[]
* @author : tangjiabin
* @date 2018/6/27 23:49
*/
private static byte[] inputToByte(InputStream inputStream) throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int rc = 0;
while ((rc = inputStream.read(buff, 0, STREAM_READ_LENGTH)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
/**
* @return void
* @Description: 绕过证书认证
* @author tangjiabin
*/
private static void turnSsl() throws Exception {
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}}, new SecureRandom());
CLIENT.setSslSocketFactory(sc.getSocketFactory());
CLIENT.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
logger.error("【http工具类错误】", e);
throw new Exception(e);
}
}
/**
* @return String
* @Description: 发送post请求
* @author tangjiabin
*/
public static String sendPost(String url, Map<String, String> param, String charset) throws Exception {
logger.info("----- begin http sendPost ----- url:{},params:{}", url, com.alibaba.fastjson.JSON.toJSONString(param));
OutputStream out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
URLConnection conn = getConnection(realUrl);
Map<String, String> defaultHeaders = new LinkedHashMap<>(3);
defaultHeaders.put("accept", "*/*");
defaultHeaders.put("connection", "Keep-Alive");
defaultHeaders.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = conn.getOutputStream();
String p = buildParams(param, charset);
if (p != null) {
// 发送请求参数
out.write(p.getBytes());
// flush输出流的缓冲
out.flush();
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
logger.error("【http工具类错误】", e);
throw new Exception(e);
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
logger.error("【http工具类错误】", ex);
}
}
logger.info("----- end http sendPost ----- result:{}", result.toString());
return result.toString();
}
/**
* @return String
* @Description: 构建参数
* @author tangjiabin
*/
public static String buildParams(Map<String, String> param, String charset) throws UnsupportedEncodingException {
if (param != null && !param.isEmpty()) {
StringBuilder buffer = new StringBuilder();
for (Map.Entry<String, String> entry : param.entrySet()) {
try {
buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), charset))
.append("&");
} catch (UnsupportedEncodingException e) {
logger.error("【http工具类错误】", e);
throw new UnsupportedEncodingException(e.getMessage());
}
}
return buffer.deleteCharAt(buffer.length() - 1).toString();
} else {
return null;
}
}
/**
* @return HttpURLConnection
* @Description: 绕过HTTPS
* @author tangjiabin
*/
private static HttpURLConnection getConnection(URL url) throws Exception {
HttpURLConnection connection;
try {
if (url.getProtocol().toUpperCase().startsWith(HTTPS)) {
SSLContext ctx = SSLContext.getInstance("SSL");
ctx.init(new KeyManager[0], new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}}, new SecureRandom());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ctx.getSocketFactory());
conn.setConnectTimeout(10000);
conn.setReadTimeout(40000);
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
connection = conn;
} else {
connection = (HttpURLConnection) url.openConnection();
}
} catch (Exception e) {
logger.error("【http工具类错误】", e);
throw new Exception(e);
}
return connection;
}
}
okHttp 工具类 绕过证书 返回文件
最新推荐文章于 2024-05-31 17:01:37 发布