Android中使用HttpGet和HttpPost访问HTTP资源

需求:用户登录(name:用户名,pwd:密码)

(一)HttpGet :doGet()方法
//doGet():将参数的键值对附加在url后面来传递

  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报头中传递

  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.         }  

-------------------------------------------------------------------------------------------------------

由此我们可知,HttpGet和HttpPost的区别在于前者是将参数在地址中传递,后者是将参数用List传递。

原文地址:https://www.cnblogs.com/leischen/p/3189161.html