Android中HttpURLConnection

大部分安卓項目開發中,網絡請求都是用封裝好的網絡框架,如:okhttp、nohttp、volley等。導致基礎的HttpURLConnection和HttpClient基本不會自己寫了,基于安卓6.0SDK刪除了HttpClient了,因此只回顧一下HttpURLConnection的用法。

Get方式:

// Get方式請求  
public static void requestByGet() throws Exception {  
    String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";  
    // 新建一個URL對象  
    URL url = new URL(path);  
    // 打開一個HttpURLConnection連接  
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
    // 設置連接超時時間  
    urlConn.setConnectTimeout(5 * 1000);  
    // 開始連接  
    urlConn.connect();  
    // 判斷請求是否成功  
    if (urlConn.getResponseCode() == HTTP_200) {  
        // 獲取返回的數據  
        byte[] data = readStream(urlConn.getInputStream());  
        Log.i(TAG_GET, "Get方式請求成功,返回數據如下:");  
        Log.i(TAG_GET, new String(data, "UTF-8"));  
    } else {  
        Log.i(TAG_GET, "Get方式請求失敗");  
    }  
    // 關閉連接  
    urlConn.disconnect();  
}  

Post方式:

// Post方式請求  
public static void requestByPost() throws Throwable {  
    String path = "https://reg.163.com/logins.jsp";  
    // 請求的參數轉換為byte數組  
    String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")  
            + "&pwd=" + URLEncoder.encode("android", "UTF-8");  
    byte[] postData = params.getBytes();  
    // 新建一個URL對象  
    URL url = new URL(path);  
    // 打開一個HttpURLConnection連接  
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
    // 設置連接超時時間  
    urlConn.setConnectTimeout(5 * 1000);  
    // Post請求必須設置允許輸出  
    urlConn.setDoOutput(true);  
    // Post請求不能使用緩存  
    urlConn.setUseCaches(false);  
    // 設置為Post請求  
    urlConn.setRequestMethod("POST");  
    urlConn.setInstanceFollowRedirects(true);  
    // 配置請求Content-Type  
    urlConn.setRequestProperty("Content-Type",  
            "application/x-www-form-urlencode");  
    // 開始連接  
    urlConn.connect();  
    // 發送請求參數  
    DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());  
    dos.write(postData);  
    dos.flush();  
    dos.close();  
    // 判斷請求是否成功  
    if (urlConn.getResponseCode() == HTTP_200) {  
        // 獲取返回的數據  
        byte[] data = readStream(urlConn.getInputStream());  
        Log.i(TAG_POST, "Post請求方式成功,返回數據如下:");  
        Log.i(TAG_POST, new String(data, "UTF-8"));  
    } else {  
        Log.i(TAG_POST, "Post方式請求失敗");  
    }  
}  
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容