httpsutil java_HttpsUtils工具类 https请求工具类

packagecom.jbcf.common.util;importjava.io.InputStream;importjava.io.OutputStream;importjava.net.HttpURLConnection;importjava.net.URL;importjava.net.URLEncoder;importjava.nio.charset.Charset;importjava.security.SecureRandom;importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;importjava.util.Arrays;importjava.util.HashMap;importjava.util.Map;importjavax.net.ssl.HostnameVerifier;importjavax.net.ssl.HttpsURLConnection;importjavax.net.ssl.SSLContext;importjavax.net.ssl.SSLSession;importjavax.net.ssl.TrustManager;importjavax.net.ssl.X509TrustManager;importcom.alibaba.fastjson.JSONObject;importcom.alibaba.fastjson.serializer.SerializerFeature;public classHttpsUtils {public static String METHOD_GET = "GET";public static String METHOD_POST = "POST";public static int DEF_CONNECT_TIMEOUT = 2 * 1000;public static int DEF_READ_TIMEOUT = 8 * 1000;public static Charset DEF_CHARSET = Charset.forName("UTF-8");public static voidmain(String[] args) {

JSONObject x=HttpsUtils.doGetAuthorization("https://amzrealtime.despatchcloud.co.uk/ws/v1/wsfulfilment/list_fulfilment_clients");

System.out.println(x);

}public staticJSONObject doGetAuthorization(String url) {

Map headers=new HashMap<>();

headers.put("Authorization", "DC 454");

String xx=HttpsUtils.Get(url, headers);returnJSONObject.parseObject(xx);

}public static TrustManager[] trustAllCerts = new TrustManager[]{newX509TrustManager() {publicjava.security.cert.X509Certificate[] getAcceptedIssuers() {return newjava.security.cert.X509Certificate[]{};

}

@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throwsCertificateException {

}

@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throwsCertificateException {

}

}};public static voidtrustAll() {try{

SSLContext sc= SSLContext.getInstance("TLS");

sc.init(null, trustAllCerts, newjava.security.SecureRandom());

HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

}catch(Exception e) {

e.printStackTrace();

}

}static{

trustAll();

}public staticString Get(String urlString) {return HttpsGo(urlString, METHOD_GET, null, null, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);

}public static String Get(String urlString, Mapheaders) {return HttpsGo(urlString, METHOD_GET, headers, null, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);

}public static String Get(String urlString, Map headers, Mapparams) {if (params != null && params.isEmpty() == false) {

StringBuffer url= newStringBuffer(urlString);try{boolean isFirst = true;if (urlString.contains("?")) {if (urlString.endsWith("&") == false && urlString.contains("&")) {

isFirst= false;

}

}else{

url.append('?');

}

String paramsEncoding=DEF_CHARSET.name();for (Map.Entryentry : params.entrySet()) {if (isFirst) isFirst = false; else url.append('&');

url.append(URLEncoder.encode(entry.getKey(), paramsEncoding));

url.append('=');

url.append(URLEncoder.encode(entry.getValue(), paramsEncoding));

}

}catch(Exception e) {

}returnGet(url.toString(), headers);

}else{returnGet(urlString, headers);

}

}public static String Post(String urlString, String contentType, byte[] content) {

Map headers = new HashMap(1);

headers.put("Content-Type", contentType);returnHttpsGo(urlString, METHOD_POST, headers, content, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);

}public staticString FormPost(String urlString, String content) {

Map headers = new HashMap(1);

headers.put("Content-Type", String.format("application/x-www-form-urlencoded; charset=%s", DEF_CHARSET.name()));return HttpsGo(urlString, METHOD_POST, null, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);

}public staticString XmlPost(String urlString, String content) {

Map headers = new HashMap(1);

headers.put("Content-Type", String.format("text/html; charset=%s", DEF_CHARSET.name()));returnHttpsGo(urlString, METHOD_POST, headers, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);

}public staticString JsonPost(String urlString, Object content) {returnJsonPost(urlString, JSONObject.toJSONString(content, SerializerFeature.DisableCircularReferenceDetect));

}public staticString JsonPost(String urlString, String content) {

Map headers = new HashMap(1);

headers.put("Content-Type", String.format("application/json; charset=%s", DEF_CHARSET.name()));returnHttpsGo(urlString, METHOD_POST, headers, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);

}public static String HttpsGo(String urlString, String method, Map headers, byte[] content, int connectTimeout, intreadTimeout) {

HttpsURLConnection conn= null;try{

conn= (HttpsURLConnection) newURL(urlString).openConnection();

SSLContext sc= SSLContext.getInstance("SSL");

sc.init(null, trustAllCerts, newSecureRandom());

conn.setHostnameVerifier(newHostnameVerifier() {

@Overridepublic booleanverify(String arg0, SSLSession arg1) {return true;

}

});

conn.setSSLSocketFactory(sc.getSocketFactory());

conn.setRequestMethod(method);

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setUseCaches(false);

conn.setConnectTimeout(connectTimeout);

conn.setReadTimeout(readTimeout);if (headers != null) {for (Map.Entryentry : headers.entrySet()) {

conn.addRequestProperty(entry.getKey(), entry.getValue());

}

}if (content != null) {if (headers == null || headers.containsKey("Content-Length") == false) {

conn.addRequestProperty("Content-Length", Integer.toString(content.length));

}

OutputStream output= null;try{

output=conn.getOutputStream();

output.write(content);

output.flush();

}finally{if (output != null) try { output.close(); } catch(Exception e) { }

}

}return readContent(conn.getResponseCode() == 200 ?conn.getInputStream() : conn.getErrorStream(), getCharset(conn));

}catch(Exception e) {return null;

}finally{if (conn != null) conn.disconnect();

}

}public static String encodeParams(Map params, String paramsEncoding) throwsException {boolean isFirst = true;

StringBuilder encodedParams= newStringBuilder();for (Map.Entryentry : params.entrySet()) {if (isFirst) isFirst = false; else encodedParams.append('&');

encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));

encodedParams.append('=');

encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));

}returnencodedParams.toString();

}public static String CHARSET_DEF =DEF_CHARSET.name();private static String CHARSET_STR = "charset=";private static int CHARSET_STR_LEN =CHARSET_STR.length();private staticString getCharset(HttpURLConnection conn) {

String contentType= conn.getHeaderField("Content-Type");int length = contentType != null ? contentType.length() : 0;if (length

}int pos = contentType != null ? contentType.indexOf("charset=") : -1;if (pos < 0) {returnCHARSET_DEF;

}return contentType.substring(pos +CHARSET_STR_LEN);

}private static String readContent(InputStream input, String charset) throwsException {try{int APPEND_LEN = 4 * 1024;int offset = 0;byte[] data = new byte[APPEND_LEN];while (true) {int len = input.read(data, offset, data.length -offset);if (len == -1) {break;

}

offset+=len;if (offset >=data.length) {

data= Arrays.copyOf(data, offset +APPEND_LEN);

}

}return charset != null ? new String(data, 0, offset, charset) : new String(data, 0, offset);

}finally{if (input != null) try { input.close(); } catch(Exception e) { }

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值