項目實戰-HttpURLConnection

HttpURLConnection

轉於:詳解HttpURLConnection

創建HttpURLConnection

任何底層的網絡連接都需要經過socket才能連接,HttpURLConnection不需要設置socket,所以,HttpURLConnection並不是底層的連接,而是在底層連接上的一個請求。這就是爲什麼HttpURLConneciton只是一個抽象類,自身不能被實例化的原因。HttpURLConnection只能通過URL.openConnection()方法創建具體的實例。

雖然底層的網絡連接可以被多個HttpURLConnection實例共享,但每一個HttpURLConnection實例只能發送一個請求。請求結束之後,應該調用HttpURLConnection實例的InputStream或OutputStream的close()方法以釋放請求的網絡資源,不過這種方式對於持久化連接沒用。對於持久化連接,得用disconnect()方法關閉底層連接的socket。

URL url = new URL("http://write.blog.csdn.net/mdeditor"); 
/*
此處的url.openConnection()對象實際上是根據URL的請求協議(此處是http)生成的URLConnection類的子類HttpURLConnection,
故此處最好將其轉化爲HttpURLConnection類型的對象,以便用到HttpURLConnection更多的API.
*/
try {
    httpURLConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
    e.printStackTrace();
}

設置HttpURLConnection參數

  • setAllowUserInteraction
  • setDoInput
  • setDoOutput
  • setIfModifiedSince
  • setUseCaches
  • setDefaultAllowUserInteraction
  • setDefaultUseCaches
// 設置請求方法,有4種方法method = GET/POST/PUT/DELETE,默認是GET 
try {
    httpURLConnection.setRequestMethod(method);
} catch (ProtocolException e) {
    e.printStackTrace();
}

// 請求不能使用緩存
httpURLConnection.setUseCaches(false);

// 設置是否向httpURLConnection輸出,如果是post請求,參數要放在http正文內,需要設爲true, 默認情況下是false
httpURLConnection.setDoOutput(doOutput);

// 設置是否從httpURLConnection讀入,默認情況下是true
httpURLConnection.setDoInput(true);

// 設置連接超時時間,防止網絡異常的情況下,可能會導致程序僵死而不繼續往下執行
httpURLConnection.setConnectTimeout(TIMEOUT_CONNECTION);

設置請求頭

HTTP請求允許一個key帶多個用逗號分開的values,但是HttpURLConnection只提供了單個操作的方法:

setRequestProperty(key,value)  //會覆蓋已經存在的key的所有values,有清零重新賦值的作用
addRequestProperty(key,value) // 在原來key的基礎上繼續添加其他value
httpURLConnection.setRequestProperty("Content-Type", contentType);

httpURLConnection.setRequestProperty("Accept-Language", language);

建立連接

// 連接,從上述url.openConnection()至此的配置必須要在connect之前完成,
httpURLConnection.connect();

/* 此處getOutputStream會隱含的進行connect
(即:如同調用上面的connect()方法,所以在開發中不調用上述的connect()也可以)
*/
OutputStream outputStream = httpURLConnection.getOutputStream();

// getInputStream()同理
InputStream inputStream = httpURLConnection.getInputStream();

HttpURLConnection發送請求

建立實際連接之後,就是發送請求,把請求參數傳到服務器,這就需要使用outputStream把請求參數傳給服務器:

  • getOutputStream
if (doOutput) {
    OutputStream outputStream = httpURLConnection.getOutputStream();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
    PrintWriter writer = new PrintWriter(outputStreamWriter, true);
    writer.write(body);
    writer.flush();
}

HttpURLConneciton獲取響應

請求發送成功之後,即可獲取響應的狀態碼,如果成功既可以讀取響應中的數據,獲取這些數據的方法包括:

  • getContent
  • getHeaderField
  • getInputStream

對於大部分請求來說,getInputStream和getContent是用的最多的。

相應的信息頭用以下方法獲取:

  • getContentEncoding
  • getContentLength
  • getContentType
  • getDate
  • getExpiration
  • getLastModifed
int statusCode = httpURLConnection.getResponseCode();

try {
    InputStream inputStream;
    if (statusCode >= HttpURLConnection.HTTP_OK
                && statusCode < HttpURLConnection.HTTP_BAD_REQUEST) {
        inputStream = httpURLConnection.getInputStream();
    } else {
        inputStream = httpURLConnection.getErrorStream();
    }

    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

    String line;
    StringBuilder builder = new StringBuilder();
    while ((line = bufferedReader.readLine()) != null) {
        builder.append(line);
    }
    return builder.toString();
} catch (Exception e) {
    e.printStackTrace();
    return null;
}

關閉連接

httpURLConnection.disconnect();
發佈了41 篇原創文章 · 獲贊 8 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章