(一)HttpGet :doGet()方法
//doGet():将参数的键值对附加在url后面来传递
- public String getResultForHttpGet(String name,String pwd) throws ClientProtocolException, IOException{
-
- String path="http://192.168.5.21:8080/test/test";
- String uri=path+"?name="+name+"&pwd="+pwd;
-
-
-
- String result="";
-
- HttpGet httpGet=new HttpGet(uri);
- HttpResponse response=new DefaultHttpClient().execute(httpGet);
- if(response.getStatusLine().getStatusCode()==200){
- HttpEntity entity=response.getEntity();
- result=EntityUtils.toString(entity, HTTP.UTF_8);
- }
- return result;
- }
(二)HttpPost :doPost()方法
//doPost():将参数打包到http报头中传递
- public String getReultForHttpPost(String name,String pwd) throws ClientProtocolException, IOException{
-
- String path="http://192.168.5.21:8080/test/test";
- HttpPost httpPost=new HttpPost(path);
- List<NameValuePair>list=new ArrayList<NameValuePair>();
- list.add(new BasicNameValuePair("name", name));
- list.add(new BasicNameValuePair("pwd", pwd));
- httpPost.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
-
- String result="";
-
- HttpResponse response=new DefaultHttpClient().execute(httpPost);
- if(response.getStatusLine().getStatusCode()==200){
- HttpEntity entity=response.getEntity();
- result=EntityUtils.toString(entity, HTTP.UTF_8);
- }
- return result;
- }
-------------------------------------------------------------------------------------------------------
由此我们可知,HttpGet和HttpPost的区别在于前者是将参数在地址中传递,后者是将参数用List传递。