Android的網路請求之HttpURLConnection封裝
阿新 • • 發佈:2021-12-20
HttpURLConnection封裝
OkHttp的封裝已經很好了,但是有時候在呼叫第三方的時候,還是需要自己來處理一下,因此簡單封裝,便於後面的使用。
public class HttpUtil { private static final int CONNECT_TIME_OUT = 15000; private static final int READ_TIME_OUT = 20000; /** * 將請求的內容轉為 url?a=b&i=j&c=d * * @param url 請求的字首 * @param paramMap 請求的引數 * @return */ public static String formatUrlWithParas(String url, Map<String, String> paramMap) { StringBuilder urlWithParas = new StringBuilder(isEmpty(url) ? "" : url); String paras = joinParas(paramMap); if (!isEmpty(paras)) { urlWithParas.append("?").append(paras); } return urlWithParas.toString(); } /** * 將請求的內容轉為 url?a=b&i=j&c=d * * @param url 請求的地址 * @param paramMap 請求的引數 * @return */ public static String formatEncodeUrlWithParas(String url, Map<String, String> paramMap) { StringBuilder urlWithParas = new StringBuilder(isEmpty(url) ? "" : url); String paras = joinParas(paramMap); if (!isEmpty(paras)) { urlWithParas.append("?").append(paras); } return urlWithParas.toString(); } /** * Http的請求 * * @param url 請求的地址 * @param headerMap 請求頭集合 * @return 請求返回的位元組資料 */ public static byte[] getRequest(String url, Map<String, String> headerMap) { return httpsRequest(url, "GET", headerMap, "", 0, CONNECT_TIME_OUT, READ_TIME_OUT, null); } /** * Http的請求 * * @param url 請求的地址 * @param headerMap 請求頭集合 * @param reqContent 請求體的內容 * @return 請求返回的位元組資料 */ public static byte[] postRequest(String url, Map<String, String> headerMap, byte[] reqContent) { return httpsRequest(url, "POST", headerMap, "", 0, CONNECT_TIME_OUT, READ_TIME_OUT, reqContent); } /** * Http的請求 * * @param url 請求的地址 * @param method 請求方法 * @param headerMap 請求頭集合 * @param connectTimeout 連線時間 * @param readTimeout 讀取時間 * @param reqContent 請求體的內容 * @return 請求返回的位元組資料 */ public static byte[] httpRequest(String url, String method, Map<String, String> headerMap, int connectTimeout, int readTimeout, byte[] reqContent) { return httpsRequest(url, method, headerMap, "", 0, connectTimeout, readTimeout, reqContent); } /** * Http的請求 * * @param url 請求的地址 * @param method 請求方法 * @param headerMap 請求頭集合 * @param proxyHost 代理主機 * @param proxyPort 代理埠 * @param connectTimeout 連線時間 * @param readTimeout 讀取時間 * @param reqContent 請求體的內容 * @return 請求返回的位元組資料 */ public static byte[] httpRequest(String url, String method, Map<String, String> headerMap, String proxyHost, final int proxyPort, int connectTimeout, int readTimeout, byte[] reqContent) { HttpURLConnection urlConnection = null; InputStream inputStream = null; try { URL serverUrl = new URL(url); if (!isEmpty(proxyHost) && proxyPort != 0) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); urlConnection = (HttpURLConnection) (serverUrl.openConnection(proxy)); } else { urlConnection = (HttpURLConnection) (serverUrl.openConnection()); } urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setRequestMethod(method); urlConnection.setConnectTimeout(connectTimeout); urlConnection.setReadTimeout(readTimeout); if (headerMap != null && headerMap.size() > 0) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { urlConnection.setRequestProperty(entry.getKey(), entry.getValue()); } } //封裝的請求頭 urlConnection.getRequestProperties(); if (reqContent != null && reqContent.length > 0) { //需要寫資料到請求體中 因為預設是GET請求,所以 urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(reqContent); outputStream.flush(); outputStream.close(); } //getInputStream()會隱式的呼叫urlConnection.connect() 並將請求體上傳至伺服器 inputStream = urlConnection.getInputStream(); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { //返回的請求頭 urlConnection.getHeaderFields(); return IOUtil.readInputStream(inputStream); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtil.close(inputStream); if (urlConnection != null) { urlConnection.disconnect(); } } return null; } /** * Https的請求 * * @param url 請求的地址 * @param headerMap 請求頭集合 * @return 請求返回的位元組資料 */ public static byte[] httpsGetRequest(String url, Map<String, String> headerMap) { return httpsRequest(url, "GET", headerMap, "", 0, CONNECT_TIME_OUT, READ_TIME_OUT, null); } /** * Https的請求 * * @param url 請求的地址 * @param headerMap 請求頭集合 * @param reqContent 請求體的內容 * @return 請求返回的位元組資料 */ public static byte[] httpsPostRequest(String url, Map<String, String> headerMap, byte[] reqContent) { return httpsRequest(url, "POST", headerMap, "", 0, CONNECT_TIME_OUT, READ_TIME_OUT, reqContent); } /** * Https的請求 * * @param url 請求的地址 * @param method 請求方法 * @param headerMap 請求頭集合 * @param connectTimeout 連線時間 * @param readTimeout 讀取時間 * @param reqContent 請求體的內容 * @return 請求返回的位元組資料 */ public static byte[] httpsRequest(String url, String method, Map<String, String> headerMap, int connectTimeout, int readTimeout, byte[] reqContent) { return httpsRequest(url, method, headerMap, "", 0, connectTimeout, readTimeout, reqContent); } /** * Https的請求 * * @param url 請求的地址 * @param method 請求方法 * @param headerMap 請求頭集合 * @param proxyHost 代理主機 * @param proxyPort 代理埠 * @param connectTimeout 連線時間 * @param readTimeout 讀取時間 * @param reqContent 請求體的內容 * @return 請求返回的位元組資料 */ public static byte[] httpsRequest(String url, String method, Map<String, String> headerMap, String proxyHost, final int proxyPort, int connectTimeout, int readTimeout, byte[] reqContent) { HttpsURLConnection urlConnection = null; InputStream inputStream = null; try { URL serverUrl = new URL(url); if (!isEmpty(proxyHost) && proxyPort != 0) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); urlConnection = (HttpsURLConnection) (serverUrl.openConnection(proxy)); } else { urlConnection = (HttpsURLConnection) (serverUrl.openConnection()); } if (url.startsWith("https")) { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}, new SecureRandom()); urlConnection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setRequestMethod(method); urlConnection.setConnectTimeout(connectTimeout); urlConnection.setReadTimeout(readTimeout); if (headerMap != null && headerMap.size() > 0) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { urlConnection.setRequestProperty(entry.getKey(), entry.getValue()); } } //封裝的請求頭 urlConnection.getRequestProperties(); if (reqContent != null && reqContent.length > 0) { //需要寫資料到請求體中 因為預設是GET請求,所以 urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(reqContent); outputStream.flush(); outputStream.close(); } //getInputStream()會隱式的呼叫urlConnection.connect() 並將請求體上傳至伺服器 inputStream = urlConnection.getInputStream(); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { //返回的請求頭 urlConnection.getHeaderFields(); return IOUtil.readInputStream(inputStream); } } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); } finally { IOUtil.close(inputStream); if (urlConnection != null) { urlConnection.disconnect(); } } return null; } /** * 將K-V的引數轉為k&v的形式 * * @param paramMap * @return */ public static String joinParas(Map<String, String> paramMap) { if (paramMap == null || paramMap.size() == 0) { return ""; } StringBuilder paras = new StringBuilder(); Iterator<Map.Entry<String, String>> ite = paramMap.entrySet().iterator(); while (ite.hasNext()) { Map.Entry<String, String> entry = ite.next(); paras.append(entry.getKey()).append("=").append(utf8Encode(entry.getValue())); if (ite.hasNext()) { paras.append("&"); } } return paras.toString(); } /** * 將K-V的引數轉為k&v的形式並進行encode編碼 * * @param paramMap * @return */ public static String joinEncodeParas(Map<String, String> paramMap) { if (paramMap == null || paramMap.size() == 0) { return ""; } StringBuilder paras = new StringBuilder(); Iterator<Map.Entry<String, String>> ite = paramMap.entrySet().iterator(); while (ite.hasNext()) { Map.Entry<String, String> entry = ite.next(); paras.append(entry.getKey()).append("=").append(entry.getValue()); if (ite.hasNext()) { paras.append("&"); } } return paras.toString(); } /** * 是否為空的判斷 * * @param str * @return */ private static boolean isEmpty(CharSequence str) { return (null == str || str.length() == 0); } /** * 將字串進行UTF-8編碼 * * @param str * @return */ private static String utf8Encode(String str) { if (!isEmpty(str) && str.getBytes().length != str.length()) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return str; } } return str; } }