httpconnection 도구 클래스
11564 단어 http산들바람HttpConnectionhttp 도구 클래스
package net.dreamlu.api.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
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 org.apache.commons.lang.StringUtils;
public class HttpKit {
private static final String DEFAULT_CHARSET = "UTF-8"; //
private static final String _GET = "GET"; // GET
private static final String _POST = "POST";// POST
/**
* http
* @param url
* @param method
* @param headers
* @return
* @throws IOException
*/
private static HttpURLConnection initHttp (String url, String method, Map<String, String> headers) throws IOException {
URL _url = new URL(url);
HttpURLConnection http = (HttpURLConnection) _url.openConnection();
//
http.setConnectTimeout(25000);
// -- ,
http.setReadTimeout(25000);
http.setRequestMethod(method);
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
if (null != headers && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
http.setRequestProperty(entry.getKey(), entry.getValue());
}
}
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
return http;
}
/**
* http
* @param url
* @param method
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyManagementException
*/
private static HttpsURLConnection initHttps (String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// SSLContext SSLSocketFactory
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL _url = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
//
http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
//
http.setConnectTimeout(25000);
// -- ,
http.setReadTimeout(25000);
http.setRequestMethod(method);
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
if (null != headers && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
http.setRequestProperty(entry.getKey(), entry.getValue());
}
}
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
return http;
}
/**
*
* @description
* : get
* @return :
*/
public static String get(String url, Map<String, String> params, Map<String, String> headers) {
StringBuffer bufferRes = null;
try {
HttpURLConnection http = null;
if (isHttps(url)) {
http = initHttps(initParams(url, params), _GET, headers);
} else {
http = initHttp(initParams(url, params), _GET, headers);
}
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
read.close();
in.close();
if (http != null) {
http.disconnect();//
}
return bufferRes.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
*
* @description
* : get
* @return :
*/
public static String get(String url) {
return get(url, null);
}
/**
*
* @description
* : get
* @return :
* @throws UnsupportedEncodingException
*/
public static String get(String url, Map<String, String> params) {
return get(url, params, null);
}
/**
*
* @description
* : POST
* @return :
*/
public static String post(String url, String params, Map<String, String> headers) {
StringBuffer bufferRes = null;
try {
HttpURLConnection http = null;
if (isHttps(url)) {
http = initHttps(url, _POST, headers);
} else {
http = initHttp(url, _POST, headers);
}
OutputStream out = http.getOutputStream();
out.write(params.getBytes(DEFAULT_CHARSET));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
read.close();
in.close();
if (http != null) {
http.disconnect();//
}
return bufferRes.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* post map
* @param url
* @param params
* @return
* @throws UnsupportedEncodingException
*/
public static String post(String url, Map<String, String> params) throws UnsupportedEncodingException {
return post(url, map2Url(params), null);
}
/**
* post map ,headers
* @param url
* @param params
* @return
* @throws UnsupportedEncodingException
*/
public static String post(String url, Map<String, String> params, Map<String, String> headers) throws UnsupportedEncodingException {
return post(url, map2Url(params), headers);
}
/**
*
* @description
* :
* @return :
* @throws UnsupportedEncodingException
*/
public static String initParams(String url, Map<String, String> params) throws UnsupportedEncodingException {
if (null == params || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder(url);
if (url.indexOf("?") == -1) {
sb.append("?");
}
sb.append(map2Url(params));
return sb.toString();
}
/**
* map url
* @description
* :
* @return :
* @throws UnsupportedEncodingException
*/
public static String map2Url(Map<String, String> paramToMap) throws UnsupportedEncodingException {
if (null == paramToMap || paramToMap.isEmpty()) {
return null;
}
StringBuffer url = new StringBuffer();
boolean isfist = true;
for (Entry<String, String> entry : paramToMap.entrySet()) {
if (isfist) {
isfist = false;
} else {
url.append("&");
}
url.append(entry.getKey()).append("=");
String value = entry.getValue();
if (StringUtils.isNotEmpty(value)) {
url.append(URLEncoder.encode(value, DEFAULT_CHARSET));
}
}
return url.toString();
}
/**
* https
* @param url
*/
private static boolean isHttps (String url) {
return url.startsWith("https");
}
/**
* https
* @param url
* @param params
* @return
*/
public class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;// true
}
}
}
//
class MyX509TrustManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
빠른 팁: SingleStoreDB의 데이터 API 사용SingleStoreDB는 HTTP 연결을 통해 SQL 문을 실행하는 데 사용할 수 있는 을 제공합니다. 이 짧은 문서에서는 이 데이터 API를 사용하는 방법에 대한 예를 보여줍니다. A는 무료 SingleStore...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.