HttpURLConnection 用法詳解

這兩天都在用HttpURLConnection這玩意兒,被其中的一個坑糾結了好久。下面是代碼。其中幾個細節需要注意,當服務端響應的狀態碼是大於200時(如401,404,。。。等)需要用getErrorStream()錯誤流來處理response響應的消息,否則無法獲取。我就是被這個坑糾結了一天。

 

package com.*.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpClientConnection {

    public static final String HTTP_POST = "POST";// post請求
    public static final String HTTP_GET = "GET";// get請求
    public static final String HTTP_PUT = "PUT"; // put請求
    public static final String CHARSET_UTF_8 = "UTF-8";// utf-8字符編碼
    public static final String CONTENT_TYPE = "application/json";// HTTP內容類型。如果未指定ContentType,默認爲TEXT/HTML
    public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";// HTTP內容類型。相當於form表單的形式
    public static final int SEND_REQUEST_TIME_OUT = 5000;// 請求超時時間
    public static final int READ_TIME_OUT = 5000;// 將讀超時時間
    
    /**
     * @param requestType 請求類型 (POST||GET||PUT...)
     * @param requestUrl 請求地址
     * @param requestParams 請求參數 (放在請求體body內的,適用於POST請求,不需要的話傳參null)
     * @return 返回服務端響應的數據
     *
     */
    public static String httpConnection(String requestType, String requestUrl, String requestParams){
         boolean isDoInput = false;
         if (requestParams != null && requestParams.length() > 0) isDoInput = true;
         OutputStream outputStream = null;
         InputStream inputStream = null;
         InputStreamReader inputStreamReader = null;
         BufferedReader reader = null;
         String tempLine = null;
         StringBuffer resultBuffer = new StringBuffer();
         try {
             HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(requestUrl).openConnection();//http的連接類
             // 設置是否向httpUrlConnection輸出,因爲這個是post請求,參數要放在http正文內,因此需要設爲true, 默認情況下是false;
             if (isDoInput) {
                 httpURLConnection.setDoOutput(true);
                 httpURLConnection.setRequestProperty("Content-Length", String.valueOf(requestParams.length()));
             }
             httpURLConnection.setDoInput(true);//設置是否從httpUrlConnection讀入
             httpURLConnection.setRequestMethod(requestType);//設定請求的方法
             httpURLConnection.setRequestProperty("Charset", CHARSET_UTF_8);//設置字符編碼
             httpURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE);//設置內容類型
             httpURLConnection.setConnectTimeout(SEND_REQUEST_TIME_OUT); //設置一個指定的超時值(以毫秒爲單位)
             httpURLConnection.setReadTimeout(READ_TIME_OUT);//將讀超時設置爲指定的超時,以毫秒爲單位。
             httpURLConnection.setUseCaches(false);//Post請求不能使用緩存
             httpURLConnection.connect();//連接
             
             //post請求的時候參數需要放在請求體內
             if (isDoInput) {
                 outputStream = httpURLConnection.getOutputStream();
                 outputStream.write(requestParams.getBytes(CHARSET_UTF_8));
                 outputStream.flush();
             }
             int responseCode = httpURLConnection.getResponseCode();
             //當responseCode 在200以上的時候必須用getErrorStream()錯誤流來處理response響應的消息,否則無法獲取
             if (responseCode >= 300) {
                 reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(),CHARSET_UTF_8));
                 while ((tempLine = reader.readLine()) != null) {
                     resultBuffer.append(tempLine);
                 }
                 throw new Exception( "HTTP Request is not success, Response code is " + responseCode + ", And Response message is " + resultBuffer.toString());
             }
             //responseCode 等於200的時候用getInputStream()正常流就ok
             if (responseCode == HttpURLConnection.HTTP_OK) {
                 reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),CHARSET_UTF_8));
                 while ((tempLine = reader.readLine()) != null) {
                     resultBuffer.append(tempLine);
                 }
             }
         } catch (MalformedURLException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }catch (Exception e) {
             e.printStackTrace();
         } finally {
            closeAll(outputStream,reader,inputStreamReader,inputStream);
        }
        //最後返回服務端響應的內容
        return resultBuffer.toString();
    }
    
    /**
     * 關閉所有流
     * @param outputStream
     * @param reader
     * @param inputStreamReader
     * @param inputStream
     */
    private static void closeAll(OutputStream outputStream, BufferedReader reader,InputStreamReader inputStreamReader, InputStream inputStream) {
         try {
             if (outputStream != null) {
                 outputStream.close();
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         try {
             if (reader != null) {
                 reader.close();
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         try {
             if (inputStreamReader != null) {
                 inputStreamReader.close();
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         try {
             if (inputStream != null) {
                 inputStream.close();
             }
         } catch (Exception e) {
             e.printStackTrace();
        }
    }
    
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章