UtilHttpByOkHttp.java 11.7 KB
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.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<OkHttpClient> localHttpClientForHttp = new ThreadLocal<OkHttpClient>();
	private static ThreadLocal<OkHttpClient> localHttpClientForHttps = new ThreadLocal<OkHttpClient>();
	
	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<String, String> headers) throws Exception {		
		return sendGet(url, headers, 60);
	}
	
	public static String sendPostForm(String url, final Map<String, String> headers, final Map<String, Object> params) throws Exception {
		return sendPostForm(url, headers, params, 60);
	}
	
	public static String sendPutForm(String url, final Map<String, String> headers, final Map<String, Object> params) throws Exception {
		return sendPutForm(url, headers, params, 60);
	}
	
	public static String sendPostString(String url, final Map<String, String> headers, final String content) throws Exception{
		return sendPostString(url, headers, content, 60);
	}
	
	public static String sendPostJson(String url, final Map<String, String> headers, String jsonStr) throws Exception{
		return sendPostJson(url, headers, jsonStr, 60);
	}
	
	public static String sendDelete(String url, final Map<String, String> headers) throws Exception {
		return sendDelete(url, headers, 60);
	}
	
	public static byte[] downloadFile(String url, final Map<String, String> headers) throws Exception{
		return downloadFile(url, headers, 60);
	}
	
	public static String sendGet(String url, final Map<String, String> 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<String, String> headers, final Map<String, Object> 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<String, String> headers, final Map<String, Object> 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<String, String> 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<String, String> 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 sendDelete(String url, final Map<String, String> 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<String, String> 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<String, String> 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<String, Object> params){
		//表单信息拼装
		FormBody.Builder builder = new FormBody.Builder(Charset.forName("UTF-8"));
		if(params != null) {
			for(Map.Entry<String, Object> entry: params.entrySet()) {
				Object tempValue = entry.getValue();
				if(tempValue.getClass().isArray()){
					String[] tempValueArr = (String[])tempValue;
					for(int i=0; i<tempValueArr.length; ++i){
						builder.add(entry.getKey()+"[]", tempValueArr[i]);
					}
				}else{
					builder.add(entry.getKey(), entry.getValue().toString());	
				}
			}
		}
		return builder.build();
	}
	
	private static RequestBody getReqeustBodyTextPlain(String content){
		return RequestBody.create(MediaType.parse("text/plain;charse=utf-8"), content);
	}
	
	private static RequestBody getReqeustBodyApplicationJson(String jsonStr){
		return RequestBody.create(MediaType.parse("application/json;charse=utf-8"), jsonStr);
	}
	
	private static Request.Builder getRequestBuilder(String url, Map<String, String> headers){
		//http头信息拼装
		Request.Builder requestBuilder = new Request.Builder().url(url);		
		if(headers != null){
			for(Map.Entry<String, String> 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<String, String> header) throws Exception {
		return sendPostFile(url, new File(filePath), fileKey, header);
	}	
	
	public static ResponseBody sendPostFile(String url, File file, String fileKey, Map<String, String> 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<String, String> headerData = new HashMap<String, String>();
		headerData.put("ss-token", "lsQUPZA2rxyckfmOD5gfnPAo9Qa6N1/EEESotlOah3t2392ZZkrhOofNAZF5zlyUrDS1Y29tLnNvbmdzaHUud2ViYXBwLnYx");
		
		Map<String, Object> paramData = new HashMap<String, Object>();
		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&timestamp=1562239191&signature=967fd77a24cbbce872bc1506a0187983", null, 0));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}