UtilHttpByOkHttp.java 11.5 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.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionSpec;
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 Map<String, OkHttpClient> localHttpClient = new HashMap<String, 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 sendPostXWwwFormUrlencodedJson(String url, Map<String, String> headers, Map<String, String> 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<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");
		String mapKey = getHttpClientMapKey(isHttps, timeoutInSecond);
		synchronized (localHttpClient) {
			client = localHttpClient.get(mapKey);
			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();
			}
			localHttpClient.put(mapKey, client);
		}		
		return client;
	}
	
	private static String getHttpClientMapKey(boolean isHttps, int timeoutInSecond) {
		if(isHttps) {
			return "HTTPS_"+timeoutInSecond;
		}else {
			return "HTTP_"+timeoutInSecond;
		}		
	}

	/**
	 * 并发请求复用连接池,避免内存溢出
	 * @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;charset=utf-8"), content);
	}
	
	private static RequestBody getReqeustBodyAapplicationXWwwFormUrlencoded(Map<String, String> data){
		String content = "";
		if(data == null) {
			return RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"), content);	
		}
		
		Iterator<String> 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<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)
                .connectionSpecs(Arrays.asList(ConnectionSpec.COMPATIBLE_TLS));
        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();
	}
		
	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();
		}
	}
}