package com.taover.util; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.Charset; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; public class UtilHttpByOkHttp { //防止线程并发,使用threadlocal管理client private static ThreadLocal localHttpClientForHttp = new ThreadLocal(); private static ThreadLocal localHttpClientForHttps = new ThreadLocal(); public static final String METHOD_GET = "GET"; public static final String METHOD_POST = "POST"; public static final String METHOD_DELETE = "DELETE"; public static final String METHOD_PUT = "PUT"; public static String sendGet(String url, final Map headers) throws Exception { return sendGet(url, headers, 60); } public static String sendPostForm(String url, final Map headers, final Map params) throws Exception { return sendPostForm(url, headers, params, 60); } public static String sendPutForm(String url, final Map headers, final Map params) throws Exception { return sendPutForm(url, headers, params, 60); } public static String sendPostString(String url, final Map headers, final String content) throws Exception{ return sendPostString(url, headers, content, 60); } public static String sendPostJson(String url, final Map headers, String jsonStr) throws Exception{ return sendPostJson(url, headers, jsonStr, 60); } public static String sendDelete(String url, final Map headers) throws Exception { return sendDelete(url, headers, 60); } public static byte[] downloadFile(String url, final Map headers) throws Exception{ return downloadFile(url, headers, 60); } public static String sendGet(String url, final Map headers, int timeoutInSecond) throws Exception { //http头信息拼装 Request request = getRequestBuilder(url, headers).get().build(); return getHttpClient(url, timeoutInSecond).newCall(request).execute().body().string(); } public static String sendPostForm(String url, final Map headers, final Map params, int timeoutInSecond) throws Exception { //请求体信息 RequestBody requestBody = getReqeustBody(params); //http头信息拼装 Request request = getRequestBuilder(url, headers).post(requestBody).build(); return getHttpClient(url, timeoutInSecond).newCall(request).execute().body().string(); } public static String sendPutForm(String url, final Map headers, final Map params, int timeoutInSecond) throws Exception { //请求体信息 RequestBody requestBody = getReqeustBody(params); //http头信息拼装 Request request = getRequestBuilder(url, headers).put(requestBody).build(); return getHttpClient(url, timeoutInSecond).newCall(request).execute().body().string(); } public static String sendPostString(String url, final Map headers, final String content, int timeoutInSecond) throws Exception{ //请求体 RequestBody requestBody = getReqeustBodyTextPlain(content); //http头信息拼装 Request request = getRequestBuilder(url, headers).post(requestBody).build(); return getHttpClient(url, timeoutInSecond).newCall(request).execute().body().string(); } public static String sendPostJson(String url, final Map headers, String jsonStr, int timeoutInSecond) throws Exception{ //请求体 RequestBody requestBody = getReqeustBodyApplicationJson(jsonStr); //http头信息拼装 Request request = getRequestBuilder(url, headers).post(requestBody).build(); return getHttpClient(url, timeoutInSecond).newCall(request).execute().body().string(); } public static String sendPostXWwwFormUrlencodedJson(String url, Map headers, Map requestBodyMap, int timeoutInSecond) throws Exception{ //请求体 RequestBody requestBody = getReqeustBodyAapplicationXWwwFormUrlencoded(requestBodyMap); //http头信息拼装 Request request = getRequestBuilder(url, headers).post(requestBody).build(); return getHttpClient(url, timeoutInSecond).newCall(request).execute().body().string(); } public static String sendDelete(String url, final Map headers, int timeoutInSecond) throws Exception { //http头信息拼装 Request request = getRequestBuilder(url, headers).delete().build(); return getHttpClient(url, timeoutInSecond).newCall(request).execute().body().string(); } public static byte[] downloadFile(String url, final Map headers, int timeoutInSecond) throws Exception{ Request request = getRequestBuilder(url, headers).get().build(); return getHttpClient(url, timeoutInSecond).newCall(request).execute().body().bytes(); } public static OkHttpClient getHttpClient(String url, int timeoutInSecond){ OkHttpClient client = null; boolean isHttps = url.trim().toLowerCase().startsWith("https"); if(isHttps){ client = localHttpClientForHttps.get(); }else{ client = localHttpClientForHttp.get(); } if(client != null){ return client; } if(isHttps){ client = buildOkHttpClientForHttps(timeoutInSecond); }else{ OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(timeoutInSecond, TimeUnit.SECONDS) .readTimeout(timeoutInSecond, TimeUnit.SECONDS) .writeTimeout(timeoutInSecond,TimeUnit.SECONDS) .retryOnConnectionFailure(true); client = builder.build(); } if(isHttps){ localHttpClientForHttps.set(client); }else{ localHttpClientForHttp.set(client); } return client; } /** * 并发请求复用连接池,避免内存溢出 * @param okHttpClient * @param url * @param headers * @param jsonStr * @return * @throws Exception */ public static String sendPostJson(OkHttpClient okHttpClient,String url, final Map headers, String jsonStr) throws Exception{ //请求体 RequestBody requestBody = getReqeustBodyApplicationJson(jsonStr); //http头信息拼装 Request request = getRequestBuilder(url, headers).post(requestBody).build(); return okHttpClient.newCall(request).execute().body().string(); } private static RequestBody getReqeustBody(Map params){ //表单信息拼装 FormBody.Builder builder = new FormBody.Builder(Charset.forName("UTF-8")); if(params != null) { for(Map.Entry entry: params.entrySet()) { Object tempValue = entry.getValue(); if(tempValue.getClass().isArray()){ String[] tempValueArr = (String[])tempValue; for(int i=0; i data){ String content = ""; if(data == null) { return RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"), content); } Iterator keyIter = data.keySet().iterator(); while(keyIter.hasNext()) { String key = keyIter.next(); String value = data.get(key); if(key == null) { continue; } if(value == null) { value=""; } try { content += key+"="+URLEncoder.encode(value, "utf-8")+"&"; } catch (UnsupportedEncodingException e) { UtilLog.errorForException(e, UtilHttpByOkHttp.class); } } return RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"), content); } private static RequestBody getReqeustBodyApplicationJson(String jsonStr){ return RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonStr); } private static Request.Builder getRequestBuilder(String url, Map headers){ //http头信息拼装 Request.Builder requestBuilder = new Request.Builder().url(url); if(headers != null){ for(Map.Entry entry: headers.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } return requestBuilder; } private static OkHttpClient buildOkHttpClientForHttps(int timeoutInSecond) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(timeoutInSecond, TimeUnit.SECONDS) .readTimeout(timeoutInSecond, TimeUnit.SECONDS) .writeTimeout(timeoutInSecond,TimeUnit.SECONDS) .retryOnConnectionFailure(true) .sslSocketFactory(getTrustedSSLSocketFactory()) .hostnameVerifier(DO_NOT_VERIFY); return builder.build(); } /** * * @param url 请求地址 * @param filePath 文件路径 * @param fileName 文件名 * @param fileKey 表单上传文件对应的key值 * @param header 请求头 * @return 只发post请求 * @throws Exception */ public static ResponseBody sendPostFile(String url, String filePath, String fileName, String fileKey, Map header) throws Exception { return sendPostFile(url, new File(filePath), fileKey, header); } public static ResponseBody sendPostFile(String url, File file, String fileKey, Map header) throws Exception { OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart(fileKey, file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)) .build(); Request request = new Request.Builder() .headers(Headers.of(header)) .url(url) .post(requestBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()){ throw new IOException("Unexpected code " + response); } return response.body(); } static TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { X509Certificate[] x509Certificates = new X509Certificate[0]; return x509Certificates; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; private static SSLSocketFactory getTrustedSSLSocketFactory() { try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); return sc.getSocketFactory(); } catch (KeyManagementException | NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } public static void main(String args[]){ String contactSsid = "lM4AeZSizgFROR/OAHmUos4BUTkf"; try { contactSsid = URLEncoder.encode(contactSsid, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String url = "https://ssep.umsapi.com/api/v1/contacts/"+contactSsid+"/messages"; System.out.println(url); Map headerData = new HashMap(); headerData.put("ss-token", "lsQUPZA2rxyckfmOD5gfnPAo9Qa6N1/EEESotlOah3t2392ZZkrhOofNAZF5zlyUrDS1Y29tLnNvbmdzaHUud2ViYXBwLnYx"); Map paramData = new HashMap(); paramData.put("kind", "text"); paramData.put("content", "小伙子 干得漂亮"); try { //System.out.println(UtilHttpByOkHttp.sendPostForm(url, headerData, paramData)); System.out.println( UtilHttpByOkHttp.sendGet("http://localhost/login/checkLogin.htm?appid=songshuyun-ifun×tamp=1562239191&signature=967fd77a24cbbce872bc1506a0187983", null, 0)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }