Requirements: User Login (name: username, pwd: password)
(i) HttpGet:d oget () method
Doget (): Attaches a key value pair of a parameter to the URL after it is passed
[Java]View Plaincopy
- public string Getresultforhttpget (String name,string pwd) throws Clientprotocolexception, ioexception{
- //server: Server project: servlet name
- String path="Http://192.168.5.21:8080/test/test";
- String uri=path+"? name=" +name+"&pwd=" +PWD;
- //name: Server-side user name, pwd: server-side password
- //Note that strings cannot be concatenated with spaces
- String result="";
- HttpGet httpget=new HttpGet (URI); Editor's note: Unlike HttpPost, this is where the parameters are passed in the address
- HttpResponse response=New Defaulthttpclient (). Execute (httpget);
- if (Response.getstatusline (). Getstatuscode () = = (){
- Httpentity entity=response.getentity ();
- Result=entityutils.tostring (Entity, HTTP. UTF_8);
- }
- return result;
- }
(ii) Httppost:dopost () method
DoPost (): Package parameters in the HTTP header pass
[Java]View Plaincopy
- public string Getreultforhttppost (String name,string pwd) throws Clientprotocolexception, ioexception{
- //server: Server project: servlet name
- 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)); //Editor's note: The difference with httpget, here is to pass the parameter with list
- String result="";
- HttpResponse response=New Defaulthttpclient (). Execute (httppost);
- if (Response.getstatusline (). Getstatuscode () = = (){
- Httpentity entity=response.getentity ();
- Result=entityutils.tostring (Entity, HTTP. UTF_8);
- }
- return result;
- }
-------------------------------------------------------------------------------------------------------
From this we know that the difference between HttpGet and HttpPost is that the former is passing the parameters in the address, the latter is passing the parameters to the list.
Use HttpGet and HttpPost to access HTTP resources in Android