Android 網路編程(3)——使用URLConnection提交請求

來源:互聯網
上載者:User

標籤:urlconnection   get   post   

URL的openConnection()方法將返回一個URLConnection對象,該對象表示應用程式和URL之間的通訊串連。程式可以通過URLConnection執行個體向該URL發送請求,讀取URL引用的資源 通常建立一個和URL的串連,並發送請求、讀取此URL引用的資源需要如下幾個步驟
  1. 通過調用URL對象openConnection()方法來建立URLConnection對象
  2. 設定URLConnection的參數和普通請求屬性
  3. 如果只是發送GET方法請求,使用connect方式建立和遠端資源之間的實際串連即可;如果需要發送POST方式的請求,需要擷取URLConnection執行個體對應的輸出資料流來發送請求參數
  4. 遠端資源變為可用,程式可以訪問遠端資源的頭欄位,或通過輸入資料流讀取遠端資源的資料
在建立和遠端資源的實際串連之前,程式可以通過如下方法來佈建要求頭欄位
  • setAllowUserInteraction:設定該URLConnection的allowUserInteraction要求標頭欄位的值
  • setDoInput:設定該URLConnection的doinput要求標頭欄位的值
  • setDoOutput:設定該URLConnection的dooutput要求標頭欄位的值
  • setIfModifiedSince:設定該URLConnection的ifModifiedSince要求標頭欄位的值
  • setUseCaches:設定該URLConnection的useCaches要求標頭欄位的值
除此之外,還可以使用如下方法來設定或增加通用頭欄位
  • setRequestProperty(String key, String value):設定該URLConnection的key要求標頭欄位的值為value,如以下代碼所示:
conn.setRequestProperty("accept","*/*");
  • addRequestProperty(String key, String value):為該URLConnection的key要求標頭欄位的增加value值,該方法並不會覆蓋原要求標頭欄位的值,而是將新值追加到原要求標頭欄位中
當遠端資源可用之後,程式可以使用以下方法用於訪問頭欄位和內容
  • Object getContent():擷取該URLConnection的內容
  • String getHeaderField(String name):擷取指定回應標頭欄位的值
  • getInputStream():返回該URLConnection對應的輸入資料流,用於擷取URLConnection響應的內容
  • getOutputStream():返回該URLConnection對應的輸出資料流,用於向URLConnection發送請求參數
如果既要使用輸入資料流讀取URLConnection響應的內容,也要使用輸出資料流發送請求參數,一定要先使用輸出資料流,在使用輸入資料流
getHeaderField()方法用於根據回應標頭欄位來返回對應的值。而某些頭欄位由於經常需要訪問,所有Java提供了以下方法來訪問特定回應標頭欄位的值
  • getContentEncoding:擷取content-enconding回應標頭欄位的值
  • getContentLength:擷取content-length回應標頭欄位的值
  • getContentType:擷取content-type回應標頭欄位的值
  • getDate():擷取date回應標頭欄位的值
  • getExpiration():擷取expires回應標頭欄位的值
  • getLastModified():擷取last-modified回應標頭欄位的值
URL請求的類別:分為二類,GET和POST請求。二者的區別在於:1)、get請求可以擷取靜態頁面,也可以把參數放在URL字串後面,傳遞給servlet(利用java編寫的服務端程式)2)、post與get的不同之處在post的參數不是放在URL字串裡面,而是放在http請求的本文內。post請求可以向伺服器傳送資料,而且資料放在HTML HEADER內一起傳送到伺服器URL地址,資料對使用者不可見。而get是把參數資料隊列加到提交的URL中,值和表單內各各個欄位一一對應,例如(http://www.baidu.com/s?w=%C4&inputT=2710)。get請求機制用的是URL地址裡面,通過?號間隔,然後以name=value的形式給用戶端傳遞參數。get傳送的資料量較小,不能大於2KB。post傳送的資料量較大,一般被預設不受限制。但理論上,IIS4中最大量為80KB,IIS5中為100KB。get安全性非常低,post安全性較高。
例子:使用URLConnection提交請求
AndroidManifest.xml——主要添加訪問網路許可權
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.url_get_post"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="19" />    <uses-permission android:name="android.permission.INTERNET"/>    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.url_get_post.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:orientation="vertical"    tools:context=".MainActivity" >    <Button         android:id="@+id/get"        android:layout_width="wrap_content"        android:layout_height="wrap_content"                android:background="#00ffff"        android:text="get"/>    <Button         android:id="@+id/post"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         android:layout_marginTop="40dp"              android:background="#00ffff"        android:text="post"/></LinearLayout>
GetPostUtil.java——get和post兩種請求方式
package com.example.url_get_post;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import java.util.List;import java.util.Map;import android.util.Log;public class GetPostUtil {/** * 向指定URL發送GET方法的請求 * @param url發送請求的URL * @param parmas請求參數,請求參數應該是name1=value1&name2=value2的形式 * @return URL所代表遠端資源的響應 */public static String sendGet(String url, String parmas){String result = "";BufferedReader bufferedReader = null;String urlName = url + "?" + parmas;try {URL realUrl = new URL(urlName);//開啟和URL之間的串連try {URLConnection urlConnection = realUrl.openConnection();/*設定通用請求屬性*///告訴WEB伺服器自己接受什麼介質類型,*/* 表示任何類型,type/* 表示該類型下的所有子類型,type/sub-type。urlConnection.setRequestProperty("accept", "*/*");urlConnection.setRequestProperty("connection", "Keep-Alive");//瀏覽器表明自己的身份(是哪種瀏覽器)urlConnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.14)");//建立實際串連urlConnection.connect();Log.e("contentType", ""+urlConnection.getContentType());Log.e("contentLength", ""+urlConnection.getContentLength());Log.e("contentEncoding", ""+urlConnection.getContentEncoding());Log.e("contentDate", ""+urlConnection.getDate());//擷取所有相應頭欄位Map<String, List<String>> map = urlConnection.getHeaderFields();//遍曆所有回應標頭欄位for (String key:map.keySet()){Log.i("GET方式請求", ""+map.get(key));}//定義BufferReader輸入資料流來讀取URL的響應bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));String line;for (;(line = bufferedReader.readLine()) != null;){result += "\n" + line;}} catch (IOException e) {// TODO Auto-generated catch blockLog.e("GET方式請求", "發送GET請求異常"+e);e.printStackTrace();}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (null != bufferedReader){try {bufferedReader.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}return result;}/** * 向指定URL發送POST方法的請求 * @param url發送請求的URL * @param parmas請求參數,請求參數應該是name1=value1&name2=value2的形式 * @return URL所代表遠端資源的響應 */public static String sendPost(String url, String parmas){String result = "";PrintWriter printWriter = null;BufferedReader bufferedReader = null;try {URL realUrl = new URL(url);//開啟和URL之間的串連try {URLConnection urlConnection = realUrl.openConnection();//設定通用請求屬性urlConnection.setRequestProperty("accept", "*/*");urlConnection.setRequestProperty("connection", "Keep-Alive");urlConnection.setRequestProperty("user-agent", "Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1; SV1)");//發送POST請求必須設定如下兩行urlConnection.setDoOutput(true);urlConnection.setDoInput(true);//擷取所有相應頭欄位Map<String, List<String>> map = urlConnection.getHeaderFields();//遍曆所有回應標頭欄位for (String key:map.keySet()){Log.i("POST方式請求", ""+map.get(key));}//擷取URLConnection對象對應的輸出資料流printWriter = new PrintWriter(urlConnection.getOutputStream());//發送請求參數printWriter.print(parmas);//flush輸出資料流緩衝printWriter.flush();//定義BufferReader輸入資料流來讀取URL的響應bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));String line;for (;(line = bufferedReader.readLine()) != null;){result += "\n" + line;}} catch (IOException e) {// TODO Auto-generated catch blockLog.e("GET方式請求", "發送GET請求異常"+e);e.printStackTrace();}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (null != bufferedReader){try {bufferedReader.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (null != printWriter){printWriter.close();}}return result;}}
MainActivity.java
package com.example.url_get_post;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.app.Activity;public class MainActivity extends Activity {private Button get,post;private String response;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                get = (Button)this.findViewById(R.id.get);        post = (Button)this.findViewById(R.id.post );                get.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubnew Thread(){@Overridepublic void run() {response = GetPostUtil.sendGet("http://www.jju.edu.cn/", null);Log.i("response", response);};}.start();}});                post.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubnew Thread(){@Overridepublic void run() {response = GetPostUtil.sendPost("http://www.jju.edu.cn/", null);//Log.i("response", response);};}.start();}});    }    }
點擊【get】按鈕,列印資訊點擊【post】按鈕,列印資訊

頭欄位資訊都是一樣的,對於post出現的異常,還沒有找到原因,先記錄下。在這裡希望大神們,指點小弟我!!!還是因為我所用的網站是我學校的網站,不能write請求?
urlConnection.setDoOutput(true);// 使用 URL 串連進行輸出urlConnection.setDoInput(true);// 使用 URL 串連進行輸入
<strong>下面有關建立URLconnection對象,與伺服器之間建立串連過程</strong>:
來自:http://www.cnblogs.com/shyang--TechBlogs/archive/2011/03/21/1990525.html
第一步是creat:URLConnection urlConnect = url.openConnection();第二步是connect:urlConnection.connect();//這兩個是不同的 在created和connected之間可以設定一些變數選項(如setDoInput,逾時等),而如果connect之後再設定就會引發異常 在需要串連才能執行的操作(如getInputStream等應用程式層操作),程式會暗中(implicitly)執行串連。一旦串連可用,就可以訪問擷取資源,如執行getInputStream()等,對於HTTPURLConnect,還有conn。getResponseCode()==200來判斷伺服器是否返回正確的應答碼以表明請求被接受。在URLConnection中,有一個域boolean connected,值為true表明已經建立到指定URL的串連,false則沒有。connect()當串連還未建立時,開啟一個communications link,而如果這個連結已經被開啟(connect值設定為true),否則ignore it
URL url = new URL("http://www.google.cn");URLConnection conn = url.openConnection();conn.setConnectTimeout(10000);conn.connect();InputStream inStream = conn.getInputStream();
當執行執行完openConnection()之後,域connected值還是false,說明這時候還未串連。等執行到connect()之後,connected才變為true,說明這時候才完成串連。而當注釋掉connect()之後,在運行程式,connected值到getInputStream執行完又變為true,getInputStream暗中執行了串連。


Android 網路編程(3)——使用URLConnection提交請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.