1. 程式人生 > >Android http請求使用介面回撥

Android http請求使用介面回撥

Android中不支援在主執行緒發起http請求資料,我們需要把http請求放到子執行緒中處理。為了保證程式碼的執行順序,可以使用介面回撥的方式拿到請求到的資料並進行處理。

定義回撥介面

public interface OnConnectResult {
    // 把請求的內容轉為String型別
    void connectResultString(String result);
}

http請求類

http請求類的結構

public class HttpUtil {
    private static final String DEFAULT_PARAMS_ENCODING = "UTF-8"
; private static final int CONNECT_TIME_OUT = 10 * 1000; private static final int READ_TIME_OUT = 30 * 1000; // 此類中的方法只處理http的GET請求 private static final String REQUEST_GET_METHOD = "GET"; // 實現http請求返回String型別的方法。 // 此方法中OnConnectResult介面型別的引數是為了返回資料 public static void performGetRequestToStringWithResult
(final String urlStr, final OnConnectResult onConnectResult) { try { if (onConnectResult == null) { return; } // 建立一個子執行緒處理http請求 new Thread(new Runnable() { @Override public
void run() { // 處理http請求 String resultStr = performGetRequestToString(urlStr); // 通過介面回撥的方式把http請求的內容返回到呼叫的地方 if (onConnectResult != null) { onConnectResult.connectResultString(resultStr); } } }).start(); } catch (Exception e) { e.printStackTrace(); } } // 處理http/https的GET請求,返回結果為String型別 public static String performGetRequestToString(String urlStr) { String result = null; HttpURLConnection httpURLConnection = null; InputStream inputStream = null; try { URL url = new URL(urlStr); // 判斷https還是http if (url.getProtocol().toLowerCase().equals("https")) { HostnameVerifier hnv = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted( java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {} @Override public void checkServerTrusted( java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {} @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; X509TrustManager[] xtmArray = new X509TrustManager[] { trustManager }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, xtmArray, new java.security.SecureRandom()); if (sslContext != null) { HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } HttpsURLConnection.setDefaultHostnameVerifier(hnv); httpURLConnection = (HttpsURLConnection) url.openConnection(); } else if (url.getProtocol().toLowerCase().equals("http")) { httpURLConnection = (HttpURLConnection) url.openConnection(); } httpURLConnection.setConnectTimeout(CONNECT_TIME_OUT); httpURLConnection.setReadTimeout(READ_TIME_OUT); httpURLConnection.setRequestMethod(REQUEST_GET_METHOD); httpURLConnection.setDoInput(true); if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = httpURLConnection.getInputStream(); // 把請求到的InputStream轉為String result = getResultString(inputStream, DEFAULT_PARAMS_ENCODING); } } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return result; } // 把InputStream轉為String private static String getResultString(InputStream inputStream, String encode) { String result = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; if (inputStream != null) { try { while ((len = inputStream.read(data)) != -1) { outputStream.write(data, 0, len); } result = new String(outputStream.toByteArray(), encode); } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } return result; } // 新增一個額外的方法,此方法把http請求強制轉為https請求 private static String httpForceToHttps(String urlStr) { try { if (urlStr == null || urlStr.isEmpty()) { return urlStr; } URL url = new URL(urlStr); String protocol = url.getProtocol().toLowerCase(); if (protocol.toLowerCase().equals("https")) { return urlStr; } if (protocol.toLowerCase().equals("http")) { String newUrlStr = urlStr.replace("http://", "https://"); return newUrlStr; } } catch (Exception e) { e.printStackTrace(); } return urlStr; } }