HttpUrlConnection 基礎使用

來源:互聯網
上載者:User

標籤:

From https://developer.android.com/reference/java/net/HttpURLConnection.html

HttpUrlConnection:

A URLConnection with support for HTTP-specific features. See the spec for details.

Uses of this class follow a pattern:

  1. Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
  2. 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.
  3. 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 getOutputStream().
  4. 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 getInputStream(). If the response has no body, that method returns an empty stream.
  5. 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.

中文釋義:

一個支援HTTP特定功能的URLConnection。

使用這個類遵循以下模式:

  1.通過調用URL.openConnection()來獲得一個新的HttpURLConnection對象,並且將其結果強制轉換為HttpURLConnection.

  2.準備請求。一個請求主要的參數是它的URI。要求標頭可能也包含中繼資料,例如認證,首選資料類型和會話cookies.

  3.可以選擇性的上傳一個請求體。HttpURLConnection執行個體必須設定setDoOutput(true),如果它包含一個請求體。通過將資料寫入一個由getOutStream()返回的輸出資料流來傳輸資料。

  4.讀取響應。回應標頭通常包含中繼資料例如響應體的內容類型和長度,修改日期和會話cookies。響應體可以被由getInputStream返回的輸入資料流讀取。如果響應沒有響應體,則該方法會返回一個空的流。

  5.關閉串連。一旦一個響應體已經被閱讀後,HttpURLConnection 對象應該通過調用disconnect()關閉。中斷連線會釋放被一個connection佔有的資源,這樣它們就能被關閉或再次使用。

 

從上面的話以及最近的學習可以總結出:

關於HttpURLConnection的操作和使用,比較多的就是GET和POST兩種了

主要的流程:

  建立URL執行個體,開啟URLConnection
URL url=new URL("http://www.baidu.com");HttpURLConnection connection= (HttpURLConnection) url.openConnection();
  設定串連參數

 常用方法:

  setDoInput

  setDoOutput

  setIfModifiedSince:設定快取頁面面的最後修改時間(參考自:http://blog.csdn.net/stanleyqiu/article/details/7717235)

  setUseCaches

  setDefaultUseCaches

  setAllowUserInteraction

  setDefaultAllowUserInteraction

  setRequestMethod:HttpURLConnection預設給使用Get方法

  佈建要求頭參數

  常用方法: 

  setRequestProperty(key,value)  

  addRequestProperty(key,value)

  setRequestProperty和addRequestProperty的區別就是,setRequestProperty會覆蓋已經存在的key的所有values,有清零重新賦值的作用。而addRequestProperty則是在原來key的基礎上繼續添加其他value。

  常用設定:

  佈建要求資料類型:

connection.setRequestProperty("Content-type","application/x-javascript->json");//json格式資料connection.addRequestProperty("Content-Type","application/x-www-form-urlencoded");//預設瀏覽器編碼類別型,http://www.cnblogs.com/taoys/archive/2010/12/30/1922186.htmlconnection.addRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);//post請求,上傳資料時的編碼類別型,並且指定了分隔字元

Connection.setRequestProperty("Content-type", "application/x-java-serialized-object");// 設定傳送的內容類型是可序列化的java對象(如果不設此項,在傳送序列化對象時,當WEB服務預設的不是這種類型時可能拋java.io.EOFException)
connection.addRequestProperty("Connection","Keep-Alive");//設定與伺服器保持串連connection.addRequestProperty("Charset","UTF-8");//設定字元編碼類型
  串連並發送請求

  connect 

  getOutputStream

  在這裡getOutStream會隱含的進行connect,所以也可以不調用connect

  擷取響應資料

  getContent (https://my.oschina.net/zhanghc/blog/134591)

  getHeaderField:擷取所有回應標頭欄位

  getInputStream

  getErrorStream:若HTTP響應表明發送了錯誤,getInputStream將拋出IOException。調用getErrorStream讀取錯誤響應。

 

執行個體:

  get請求:

  

public static String get(){        String message="";        try {            URL url=new URL("http://www.baidu.com");            HttpURLConnection connection= (HttpURLConnection) url.openConnection();            connection.setRequestMethod("GET");            connection.setConnectTimeout(5*1000);            connection.connect();            InputStream inputStream=connection.getInputStream();            byte[] data=new byte[1024];            StringBuffer sb=new StringBuffer();            int length=0;            while ((length=inputStream.read(data))!=-1){                String s=new String(data, Charset.forName("utf-8"));                sb.append(s);            }            message=sb.toString();            inputStream.close();            connection.disconnect();        } catch (Exception e) {            e.printStackTrace();        }        return message;    }

  post請求:

 

public static String post(){        String message="";        try {            URL url=new URL("http://119.29.175.247/wikewechat/Admin/Login/login.html");            HttpURLConnection connection= (HttpURLConnection) url.openConnection();            connection.setRequestMethod("POST");            connection.setDoOutput(true);            connection.setDoInput(true);            connection.setUseCaches(false);            connection.setConnectTimeout(30000);            connection.setReadTimeout(30000);            connection.setRequestProperty("Content-type","application/x-javascript->json");            connection.connect();            OutputStream outputStream=connection.getOutputStream();            StringBuffer sb=new StringBuffer();            sb.append("email=");            sb.append("[email protected]&");            sb.append("password=");            sb.append("1234&");            sb.append("verify_code=");            sb.append("4fJ8");            String param=sb.toString();            outputStream.write(param.getBytes());            outputStream.flush();            outputStream.close();            Log.d("ddddd","responseCode"+connection.getResponseCode());            InputStream inputStream=connection.getInputStream();            byte[] data=new byte[1024];            StringBuffer sb1=new StringBuffer();            int length=0;            while ((length=inputStream.read(data))!=-1){                String s=new String(data, Charset.forName("utf-8"));                sb1.append(s);            }            message=sb1.toString();            inputStream.close();            connection.disconnect();        } catch (Exception e) {            e.printStackTrace();        }        return message;    }

 

  post上傳圖片和表單資料:

public static String uploadFile(File file){
String message="";
String url="http://119.29.175.247/uploads.php";
String boundary="7786948302";
Map<String ,String> params=new HashMap<>();
params.put("name","user");
params.put("pass","123");
try {
URL url1=new URL(url);
HttpURLConnection connection= (HttpURLConnection) url1.openConnection();
connection.setRequestMethod("POST");
connection.addRequestProperty("Connection","Keep-Alive");
connection.addRequestProperty("Charset","UTF-8");
connection.addRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
// 設定是否向httpUrlConnection輸出,因為這個是post請求,參數要放在
// http本文內,因此需要設為true, 預設情況下是false;
connection.setDoOutput(true);
//設定是否從httpUrlConnection讀入,預設情況下是true;
connection.setDoInput(true);
// Post 請求不能使用緩衝 ?
connection.setUseCaches(false);
connection.setConnectTimeout(20000);
DataOutputStream dataOutputStream=new DataOutputStream(connection.getOutputStream());
FileInputStream fileInputStream=new FileInputStream(file);
dataOutputStream.writeBytes("--"+boundary+"\r\n");
// 設定傳送的內容類型是可序列化的java對象
// (如果不設此項,在傳送序列化對象時,當WEB服務預設的不是這種類型時可能拋java.io.EOFException)
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ URLEncoder.encode(file.getName(),"UTF-8")+"\"\r\n");
dataOutputStream.writeBytes("\r\n");
byte[] b=new byte[1024];
while ((fileInputStream.read(b))!=-1){
dataOutputStream.write(b);
}
dataOutputStream.writeBytes("\r\n");
dataOutputStream.writeBytes("--"+boundary+"\r\n");
try {
Set<String > keySet=params.keySet();
for (String param:keySet){
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\""
+encode(param)+"\"\r\n");
dataOutputStream.writeBytes("\r\n");
String value=params.get(param);
dataOutputStream.writeBytes(encode(value)+"\r\n");
dataOutputStream.writeBytes("--"+boundary+"\r\n");

}
}catch (Exception e){

}

InputStream inputStream=connection.getInputStream();
byte[] data=new byte[1024];
StringBuffer sb1=new StringBuffer();
int length=0;
while ((length=inputStream.read(data))!=-1){
String s=new String(data, Charset.forName("utf-8"));
sb1.append(s);
}
message=sb1.toString();
inputStream.close();
fileInputStream.close();
dataOutputStream.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return message;
}

private static String encode(String value) throws UnsupportedEncodingException {
return URLEncoder.encode(value,"UTF-8");
}

 這裡需要指出:

通過chrome的開發工具截取的頭資訊可以看到:

通過post上傳資料時,若除了文本資料以外還要需要上傳檔案,則需要在指定每一條資料的Content-Disposition,name,若是檔案還要指明filename,並在每條資料轉送的後面用boundary隔開。

HttpUrlConnection 基礎使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.