There are several ways that Android can submit data to the server, how they use it, here we explore.
The example here is to submit the client's username and password, and the Streamtools.readinputstream (is); The function is to transfer the input into a string, which is a public class. I've introduced it earlier. Http://www.cnblogs.com/fengtengfei/p/3969520.html, this is not a duplicate explanation.
First type: GET
The key parts are:
First we use URL wrapper to access the path, because it is a GET request, when learning javaweb we know that, the path to the parameters to be submitted to assemble.
Then we openconnection (), it returns the httpurlconnection object, we can make the relevant parameters, and the timeout setting, and get the return code of the server.
URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"); int code = Conn.getresponsecode ();
Example
1 Public Staticstring loginbyget (string username,string password) {2 //submit data to outgoing server3String Path =NULL;4 Try {5Path = "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 block8 e1.printstacktrace ();9 }Ten One Try { AURL url =NewURL (path); - -HttpURLConnection conn =(HttpURLConnection) url.openconnection (); theConn.setconnecttimeout (5000); -Conn.setrequestmethod ("GET"); - - + intCode =Conn.getresponsecode (); - if(code==200){ + //Request succeeded AInputStream is =Conn.getinputstream (); atString result =Streamtools.readinputstream (IS); - - returnresult; -}Else{ - return NULL; - } in - to}Catch(Exception e) { + //TODO auto-generated Catch block - e.printstacktrace (); the return NULL; * } $ Panax Notoginseng}
Second type: Post
In the comparison between the Get and post requests of the Web page, we know that the post is a few more parameters than get, so here we have to set the relevant parameters,
The first thing we want to set up is Content-type and 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 () +" " );
Second, theway the post is actually the browser to write the data to the server. So we're going to set the parameters so that the server allows us to have write permissions,
Conn.setdooutput (TRUE); OutputStream os = Conn.getoutputstream (); Os.write (Data.getbytes ());
Example:
1 Public Staticstring loginbypost (string username,string password) {2 //Post submit data to outgoing server3String Path = "Http://192.168.254.100:8080/web/LoginServlet";4 5 Try {6URL url =NewURL (path);7 8HttpURLConnection conn =(HttpURLConnection) url.openconnection ();9Conn.setconnecttimeout (5000);TenConn.setrequestmethod ("POST"); One //prepare the data and calculate its length AString 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 is actually a browser that writes data to the server. - //Allow Write Data -Conn.setdooutput (true); +OutputStream OS =Conn.getoutputstream (); - Os.write (Data.getbytes ()); +System.out.println ("2"); A at intCode =Conn.getresponsecode (); - if(code==200){ - //Request succeeded -InputStream is =Conn.getinputstream (); -String result =Streamtools.readinputstream (IS); in - returnresult; to}Else{ + return NULL; - } the * $}Catch(Exception e) {Panax Notoginseng //TODO auto-generated Catch block - e.printstacktrace (); the return NULL; + } A the}
The third type: Httpclientget
Using the step is, we first to instantiate a HttpClient object, but also to instance a HttpGet object, let HttpClient object to execute (HttpGet object), then we can get HttpResponse object, The two are the returned objects of the server, so the difference is here.
Here the return code is obtained by Response.getstatusline (). Getstatuscode (); Be careful in use.
Example
Public Staticstring loginbyhttpclientget (string username,string password) {Try{HttpClient Client=Newdefaulthttpclient (); String Path= "Http://192.168.254.100:8080/web/LoginServlet?username=" +urlencoder.encode (username) + "&password=" +urlencoder.encode (password); HttpGet HttpGet=Newhttpget (path); //perform the action. Hit EnterHttpResponse response =Client.execute (HttpGet); intCode =response.getstatusline (). Getstatuscode (); if(code==200){ //Request succeededInputStream is =response.getentity (). getcontent (); String result=Streamtools.readinputstream (IS); returnresult; }Else{ return NULL; } } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); return NULL; } }
Fourth type: Httpclientpost
The difference between Httpclientpost and Httpclientget is that the HttpPost is to specify the data entity to commit, and the implementation here is like a map, so this is the most convenient way to have more parameters.
list<namevaluepair> parameters = new arraylist<namevaluepair> ();p Arameters.add (New Basicnamevaluepair (" Username ", username));p arameters.add (New Basicnamevaluepair (" password ", password));
Example
Public Staticstring loginbyhttpclientpost (string username,string password) {Try{HttpClient Client=Newdefaulthttpclient (); String Path= "Http://192.168.254.100:8080/web/LoginServlet"; HttpPost Post=NewHttpPost (); //specify the data entity to commitlist<namevaluepair> parameters =NewArraylist<namevaluepair>(); Parameters.Add (NewBasicnamevaluepair ("username", username)); Parameters.Add (NewBasicnamevaluepair ("Password", password)); Post.setentity (NewUrlencodedformentity (Parameters, "Utf-8")); HttpResponse Response=Client.execute (POST); intCode =response.getstatusline (). Getstatuscode (); if(code==200){ //Request succeededInputStream is =response.getentity (). getcontent (); String result=Streamtools.readinputstream (IS); returnresult; }Else{ return NULL; } } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); return NULL; } }
Darren
Weibo: @IT_ Siege Division
Source: http://www.cnblogs.com/fengtengfei/
Get,post,httpget,httppost use of Android data and server interaction