Android中使用HttpGet和HttpPost訪問HTTP資源

需求:用戶登陸(name:用戶名,pwd:密碼)php

(一)HttpGet :doGet()方法
//doGet():將參數的鍵值對附加在url後面來傳遞java

[java]  view plain copy
  1. public String getResultForHttpGet(String name,String pwd) throws ClientProtocolException, IOException{  
  2.                 //服務器  :服務器項目  :servlet名稱  
  3.                 String path="http://192.168.5.21:8080/test/test";  
  4.                 String uri=path+"?name="+name+"&pwd="+pwd;  
  5.                 //name:服務器端的用戶名,pwd:服務器端的密碼  
  6.                 //注意字符串鏈接時不能帶空格  
  7.                  
  8.                 String result="";  
  9.                  
  10.                 HttpGet httpGet=new HttpGet(uri);//編者按:與HttpPost區別所在,這裏是將參數在地址中傳遞  
  11.                 HttpResponse response=new DefaultHttpClient().execute(httpGet);  
  12.                 if(response.getStatusLine().getStatusCode()==200){  
  13.                         HttpEntity entity=response.getEntity();  
  14.                         result=EntityUtils.toString(entity, HTTP.UTF_8);  
  15.                 }  
  16.                 return result;  
  17.         }  

(二)HttpPost :doPost()方法
//doPost():將參數打包到http報頭中傳遞服務器

[java]  view plain copy
  1. public String getReultForHttpPost(String name,String pwd) throws ClientProtocolException, IOException{  
  2.                 //服務器  :服務器項目  :servlet名稱  
  3.                 String path="http://192.168.5.21:8080/test/test";  
  4.                 HttpPost httpPost=new HttpPost(path);  
  5.                 List<NameValuePair>list=new ArrayList<NameValuePair>();  
  6.                 list.add(new BasicNameValuePair("name", name));  
  7.                 list.add(new BasicNameValuePair("pwd", pwd));  
  8.                 httpPost.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));//編者按:與HttpGet區別所在,這裏是將參數用List傳遞  
  9.                  
  10.                 String result="";  
  11.                  
  12.                 HttpResponse response=new DefaultHttpClient().execute(httpPost);  
  13.                 if(response.getStatusLine().getStatusCode()==200){  
  14.                         HttpEntity entity=response.getEntity();  
  15.                         result=EntityUtils.toString(entity, HTTP.UTF_8);  
  16.                 }  
  17.                 return result;  
  18.         }  

-------------------------------------------------------------------------------------------------------app

由此咱們可知,HttpGet和HttpPost的區別在於前者是將參數在地址中傳遞,後者是將參數用List傳遞。oop

相關文章
相關標籤/搜索