用http协议调用接口

public class HttpUtil {

private static Log log = LogFactory.getLog(HttpUtil.class);  
  
/** 
 * 定义编码格式 UTF-8 
 */  
public static final String URL_PARAM_DECODECHARSET_UTF8 = "UTF-8";  
  
/** 
 * 定义编码格式 GBK 
 */  
public static final String URL_PARAM_DECODECHARSET_GBK = "GBK";  

private static int connectionRequestTimeout = 120000;
private static int connectionTimeOut = 120000;  
private static int socketTimeOut = 120000;  

private static CloseableHttpClient getHttpClient() {
	RequestConfig requestConfig = RequestConfig.custom()
			.setConnectionRequestTimeout(connectionRequestTimeout)
			.setConnectTimeout(connectionTimeOut)
			.setSocketTimeout(socketTimeOut).build();
	return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
}
	 
private static CloseableHttpClient getSSLHttpClient() {
	try {
    	SSLContext context = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
    	 
	    	@Override
	    	public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	    		return true;
	    	}
    	}).build();
    	SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(context);
    	RequestConfig requestConfig = RequestConfig.custom()
    			.setConnectionRequestTimeout(connectionRequestTimeout)
    			.setConnectTimeout(connectionTimeOut)
    			.setSocketTimeout(socketTimeOut).build();
    	return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(requestConfig).build();
	} catch (KeyManagementException e) {
		log.error("ssl context key management Exception {}", e);
    	throw new BaseException("ssl context key management Exception", e);
	} catch (NoSuchAlgorithmException e) {
		log.error("ssl context get instance faild, no such method {}", e);
    	throw new BaseException("ssl context get instance faild", e);
	} catch (KeyStoreException e) {
		log.error("ssl context key store Exception {}", e);
    	throw new BaseException("ssl context key store Exception", e);
	}
}
  
/** 
 * POST方式提交数据 
 * @param url 
 *          待请求的URL 
 * @param params 
 *          要提交的数据 
 * @param enc 
 *          编码 
 * @return 
 *          响应结果 
 * @throws ClientProtocolException 
 * @throws IOException 
 *          IO异常 
 */  
public static String URLPost(String url, Map headers, Map params) throws ClientProtocolException, IOException{  
	CloseableHttpClient client = getSSLHttpClient();
	HttpPost post = new HttpPost(url);
	for (Map.Entry header : headers.entrySet()) {
		post.setHeader(header.getKey(), header.getValue());
	}
	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(buildPairList(params), getDefaultCharset(null));
	post.setEntity(entity);

// HttpHost host = new HttpHost(“ali.ugamenow.com”, 443, “https”);
// HttpContext context = createBasicAuthContext(“alibaba”, “JhtF5d53Fdgl9d”, host);
CloseableHttpResponse response = null;
try {
response = client.execute(post);
if (response == null || response.getStatusLine() == null || response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
log.error(“HttpUtil do http get request failed”);
throw new BaseException(“HttpUtil do http get request failed”);
}
HttpEntity httpEntity = response.getEntity();
if (httpEntity == null) {
return StringUtils.EMPTY;
}
String result = EntityUtils.toString(httpEntity, getDefaultCharset(httpEntity));
EntityUtils.consume(httpEntity);
return result;
} finally {
try {
if(response != null){
response.close();
}
client.close();
} catch (IOException e) {
log.error(“warning : httpRequestc close fail”, e);
}
}
}

/** 
 * GET方式提交数据 
 * @param url 
 *          待请求的URL 
 * @param params 
 *          要提交的数据 
 * @param enc 
 *          编码 
 * @return 
 *          响应结果 
 * @throws ClientProtocolException 
 * @throws IOException 
 *          IO异常 
 */  
public static String doHttpGet(String url, Map params, Map headers) throws ClientProtocolException, IOException {
	CloseableHttpClient httpClient = null;
	if (StringUtils.startsWith(url, "https")) {
		httpClient = getSSLHttpClient();
	} else {
		httpClient = getHttpClient();
	}
	String queryUri = URLEncodedUtils.format(buildPairList(params), getDefaultCharset(null));
	HttpGet httpGet = new HttpGet(url + "?" + queryUri);
	RequestConfig requestConfig = RequestConfig.custom()
			.setConnectionRequestTimeout(connectionRequestTimeout)
			.setConnectTimeout(connectionTimeOut)
			.setSocketTimeout(socketTimeOut).build();
	httpGet.setConfig(requestConfig);
	for (Map.Entry header : headers.entrySet()) {
    	httpGet.addHeader(header.getKey(), header.getValue());
	}
	CloseableHttpResponse response = null;
	try {
		response = httpClient.execute(httpGet);
    	if (response == null || response.getStatusLine() == null || response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
	    	log.error("HttpUtil do http get request failed");
	    	throw new BaseException("HttpUtil do http get request failed");
    	}
    	HttpEntity httpEntity = response.getEntity();
    	if (httpEntity == null) {
    		return StringUtils.EMPTY;
    	}
    	String result = EntityUtils.toString(httpEntity, getDefaultCharset(httpEntity));
    	EntityUtils.consume(httpEntity);
    	return result;
	} finally {
    	try {
    	    if(response != null){
                response.close();
    	    }
            httpClient.close();
    	} catch (IOException e) {
	    	log.error("HttpUtil close httpClient occurs IOException {}", e);
    	}
	}
}

private static List buildPairList(Map params) {
	if (params == null || params.isEmpty()) {
		return new ArrayList();
	}
	List pairList = new ArrayList();
	for (Map.Entry entry : params.entrySet()) {
    	if (entry == null)
	    	continue;
	    pairList.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
    }
	log.info("HttpUtil's name value pair size {}" + pairList.size());
    return pairList;
}
	 
private static Charset getDefaultCharset(HttpEntity entity) {
	if (entity == null){
    	return Charset.forName(CharEncoding.UTF_8);
	}
	ContentType contentType = ContentType.getOrDefault(entity);
	return contentType.getCharset();
}

//add by 15042020 start 20161012
public static String getHttpCode(String url, String requestContent) {

	String result =null;
	HttpClient httpClient = getHttpClient();
	try {
		// 创建Get方法实例
		HttpPut httpPut = new HttpPut(url);
		// 添加Content
		if (!StringUtil.isEmpty(requestContent)) {
			  StringEntity entity = new StringEntity(requestContent,"UTF-8");
			  entity.setContentType("application/json;charset=UTF-8");
			  entity.setContentEncoding("UTF-8");
			  httpPut.setEntity(entity);
		}

		HttpResponse httpResponse = httpClient.execute(httpPut);

		int httpCode = httpResponse.getStatusLine().getStatusCode();
		
		result=String.valueOf(httpCode);

/* if (httpCode == HttpURLConnection.HTTP_OK || httpCode == HttpURLConnection.HTTP_NO_CONTENT) {
String responseContent = EntityUtils.toString(httpResponse.getEntity());
result = responseContent;
}*/

	} catch (Exception ex) {
		log.error("", ex);
	} finally {
		httpClient.getConnectionManager().shutdown();
	}
	return result;
}

public static String getMethod(String url, String contentType) {
	String result = null;
	HttpClient httpClient = getHttpClient();
	try {
		// 创建Get方法实例
		HttpGet httpGet = new HttpGet(url);
		httpGet.setHeader("Content-Type", contentType);
		HttpResponse response = httpClient.execute(httpGet);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			//InputStream instreams = entity.getContent();
			//result = StringUtil.convertStreamToString(instreams);
			result = EntityUtils.toString(entity, "UTF-8");
		}
	} catch (ClientProtocolException cpe) {
		// TODO For ClientProtocolException
		log.error("", cpe);
	} catch (IOException ioe) {
		// TODO For IOException
		log.error("", ioe);
	} finally {
		httpClient.getConnectionManager().shutdown();
	}

	return result;
}
//add by 15042020 end 20161012

public static String doPostWithJsonInString(String url, String json){
    HttpClient client = getHttpClient();
    HttpPost post = new HttpPost(url);
    String response = null;
    try {
        StringEntity s = new StringEntity(json);
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");    // 发送json数据需要设置contentType
        post.setEntity(s);
        HttpResponse res = client.execute(post);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            HttpEntity entity = res.getEntity();
            response = EntityUtils.toString(entity);    // 返回json格式
        }
    } catch (Exception e) {
        throw new BaseException(e);
    }
    return response;
}

public static String doPostWithFormData(String url, Map parameters) throws ClientProtocolException, IOException {
	/*HttpUtil2 httpUtil = new HttpUtil2();
	HttpResponseModel response = httpUtil.sendRequest(url, "post", parameters,
			"application/x-www-form-urlencoded");
	if (response==null) {
		return null;
	}
	
	return response.getContent();*/
	
	Map headers = new HashMap<>();
	headers.put("Content-Type", "application/x-www-form-urlencoded");
	
	Map params = new HashMap<>();
	if (parameters!=null && !parameters.isEmpty()) {
		Iterator keys = parameters.keySet().iterator();
		while(keys.hasNext()) {
			String key = keys.next();
			String value = parameters.get(key);
			params.put(key, value);
		}
	}
	
	return URLPost(url, headers, params);
}

}

你可能感兴趣的:(Java,http工具类)