Android資料與伺服器互動的GET,POST,HTTPGET,HTTPPOST的使用

來源:互聯網
上載者:User

標籤:android   style   blog   http   color   io   os   使用   java   

 

Android有這幾種方式,可以提交資料到伺服器,他們是怎麼使用的呢,這裡我們來探討一下。

這裡的例子用的都是提交用戶端的使用者名稱及密碼,同時本節用到的StreamTools.readInputStream(is);作用是把輸入資料流轉化為字串,是一個公用類。我在前面介紹過了。http://www.cnblogs.com/fengtengfei/p/3969520.html,這裡就不在重複的說明了。

第一種:GET

關鍵區段是:

首先我們用URL封裝訪問的路徑,由於是get請求,在學習javaWEB的時候我們就以及知道了,路徑中要把提交的參數拼裝。

然後我們openConnection(),其返回的是HttpURLConnection對象,拿到這個對象我們就可以進行相關參數,及逾時的設定,以及擷取伺服器的返回碼了。

URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");int code = conn.getResponseCode();

 

example:

 1 public static String loginByGet(String username,String password) { 2         //提交資料到發伺服器 3         String path = null; 4         try { 5             path = "http://192.168.254.100:8080/web/LoginServlet?username="+URLEncoder.encode(username,"utf-8")+"&password="+password; 6         } catch (UnsupportedEncodingException e1) { 7             // TODO Auto-generated catch block 8             e1.printStackTrace(); 9         }10         11         try {12             URL url = new URL(path);13             14             HttpURLConnection conn = (HttpURLConnection) url.openConnection();15             conn.setConnectTimeout(5000);16             conn.setRequestMethod("GET");17             18             19             int code = conn.getResponseCode();20             if(code==200){21                 //請求成功22                 InputStream is = conn.getInputStream();23                 String result = StreamTools.readInputStream(is);24                 25                 return result;26             }else{27                 return null;28             }29             30             31         } catch (Exception e) {32             // TODO Auto-generated catch block33             e.printStackTrace();34             return null;35         }36         37     }

 

第二種:Post

在網頁的get與post的請求的對比中我們知道post比get多了幾個參數,所以這裡我們也是要對相關參數進行設定的,

首先我們要設定的是Content-type與Cotent-Length,

           String data = "username="+URLEncoder.encode(username,"utf-8")+"&password="+password;conn.setRequestProperty("Content-Type:", "application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length:", data.length()+"");

 其次,post的方式,實際上是瀏覽器把資料寫給伺服器。所以我們要設定相關參數,讓伺服器允許我們有寫的許可權,

          conn.setDoOutput(true);OutputStream os = conn.getOutputStream();os.write(data.getBytes());

 example:

 1 public static String loginByPost(String username,String password){ 2         //POST提交資料到發伺服器 3         String path = "http://192.168.254.100:8080/web/LoginServlet"; 4          5         try { 6             URL url = new URL(path); 7              8             HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 9             conn.setConnectTimeout(5000);10             conn.setRequestMethod("POST");11             //準備資料,計算其長度12             String data = "username="+URLEncoder.encode(username,"utf-8")+"&password="+password;13             conn.setRequestProperty("Content-Type:", "application/x-www-form-urlencoded");14             conn.setRequestProperty("Content-Length:", data.length()+"");16             //post的方式,實際上是瀏覽器把資料寫給伺服器。17             //允許寫資料18             conn.setDoOutput(true);19             OutputStream os = conn.getOutputStream();20             os.write(data.getBytes());21             System.out.println("2");22             23             int code = conn.getResponseCode();25             if(code==200){26                 //請求成功27                 InputStream is = conn.getInputStream();28                 String result = StreamTools.readInputStream(is);29                 30                 return result;31             }else{32                 return null;33             }34             35             36         } catch (Exception e) {37             // TODO Auto-generated catch block38             e.printStackTrace();39             return null;40         }41         42     }

 

第三種:httpclientget

使用步驟是,我們首先要執行個體化一個HttpClient的對象,同時也要執行個體一個HttpGet的對象,讓HttpClient的對象去execute(HttpGet的對象),這時我們可以得到HttpResponse的對象,二者就是伺服器的返回的對象,所以區別就在這裡了。

這裡的返回碼是這樣獲得的response.getStatusLine().getStatusCode();使用中要注意。

 

example:

public static String loginByHttpClientGet(String username,String password){        try {            HttpClient client = new DefaultHttpClient();            String path = "http://192.168.254.100:8080/web/LoginServlet?username="            +URLEncoder.encode(username)+"&password="+URLEncoder.encode(password);            HttpGet httpGet = new HttpGet(path);            //執行操作。敲斷行符號            HttpResponse response = client.execute(httpGet);            int code = response.getStatusLine().getStatusCode();            if(code==200){                //請求成功                InputStream is = response.getEntity().getContent();                String result = StreamTools.readInputStream(is);                                return result;            }else{                return null;            }        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();            return null;        }    }

 

第四種:httpclientpost

採用HttpClientPost的方式與HttpClientGet的方式的區別是HttpPost要指定提交的資料實體,而這裡的實現就像是map,所以對於參數較多的時候,這種方式是最為便捷的。

                List<NameValuePair> parameters = new ArrayList<NameValuePair>();parameters.add(new BasicNameValuePair("username", username));parameters.add(new BasicNameValuePair("password", password));            

 example:

public static String loginByHttpClientPost(String username,String password){        try {            HttpClient client = new DefaultHttpClient();            String path = "http://192.168.254.100:8080/web/LoginServlet";            HttpPost post = new HttpPost();            //指定要提交的資料實體            List<NameValuePair> parameters = new ArrayList<NameValuePair>();            parameters.add(new BasicNameValuePair("username", username));            parameters.add(new BasicNameValuePair("password", password));            post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));                        HttpResponse response = client.execute(post);                        int code = response.getStatusLine().getStatusCode();            if(code==200){                //請求成功                InputStream is = response.getEntity().getContent();                String result = StreamTools.readInputStream(is);                                return result;            }else{                return null;            }                    } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();            return null;        }    }

 

Darren

微博:@IT_攻城師

出處:http://www.cnblogs.com/fengtengfei/

 

Android資料與伺服器互動的GET,POST,HTTPGET,HTTPPOST的使用

聯繫我們

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