Android——HttpUrlConnection
阿新 • • 發佈:2019-01-08
歡迎訪問我的個人部落格,一起學習交流。^_^
1. 開發者文件 API
A URLConnection with support for HTTP-specific features. See the spec for details.
Uses of this class follow a pattern:
- Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
- Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
- Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by URLConnection.getOutputStream().
- Read the response. Response headers typically include metadata such as the response body’s content type and length, modified dates and session cookies. The response body may be read from the stream returned by URLConnection.getInputStream(). If the response has no body, that method returns an empty stream.
- Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.
2. 解釋一下
- 通過呼叫URL.openConnection()並將結果轉換為HttpURLConnection,可以獲得一個新的HttpURLConnection。
- 準備請求。請求的主要屬性是其URI。請求頭還可能包括元資料,如憑證、首選內容型別和會話cookie。
- 可選地上載請求主體。如果例項包含請求體,則必須使用setDoOutput(true)配置例項。通過寫入URLConnection.getOutputStream()返回的流來傳輸資料。
- 讀取響應。響應頭通常包括元資料,如響應主體的內容型別和長度、修改日期和會話cookie。響應體可以從URLConnection.getInputStream()返回的流中讀取。如果響應沒有主體,則該方法返回一個空流。
- 斷開連線。一旦讀取了響應體,應該通過呼叫disconnect()關閉HttpURLConnection。斷開連線釋放連線所持有的資源,以便它們可以被關閉或重用。
3. 實踐
private void sendRequestWithHttpRulConnection(){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL("https://www.baidu.com");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder reponse = new StringBuilder();
String line;
while((line = reader.readLine()) != null){
reponse.append(line);
}
showResponse(reponse.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
if(connection != null){
connection.disconnect();
}
}
}
}).start();
}
首先需要獲取到HttpUrlConnection 的例項,一般只需new出一個URL 物件,並傳入目標的網路地址,然後呼叫一下 openConnection() 方法即可。
在得到了HttpUrlConnection例項後,我們可以設定一下HTTP請求所用的方法:GET和POST。GET表示希望從伺服器那裡獲取資料,而POST則表示希望提交資料給伺服器。
接下來就可以進行一些自由的定製了,比如設定連線超時、讀取超時的毫秒數,以及伺服器希望得到的一些訊息頭等。
之後再呼叫getInputStream() 方法就可以獲取到伺服器返回的資料了,剩下的任務就是對輸入流進行讀取。
最後呼叫disconnect() 方法將這個HTTP連線關閉掉。
如果使用POST方法,需設定connection.setDoOutput(true),再在獲取輸入流之前把要提交的資料寫出即可,注意每條資料都要以鍵值對的形式存在,資料與資料之間用“&”符號隔開,for example:
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");