I. Sending a GET request using URLConnection
1. Establish a connection to the server:
URLConnection connection=new URL ("https://www.baidu.com/"). OpenConnection ();
2. Set the request header (the cookie can also be set by the request header):
connection.setrequestproperty ("Referer", "https://www.baidu.com/");
Connection.setrequestproperty ("Cookie", "BIDUPSID=844B9321236FFD30C304AE4CCEE0602A; bd_upn=12314753");
3. Get response information:
(1): It is recommended to use StringBuilder stitching string;
(2): If new Stream object do not forget close.
Note the closing order: turn off the order to be associated with new.
Abstract understanding: Go home from work to sleep first into the community, then into the home, then into the bedroom, work will first out of the bedroom, then out of the home, finally out of the community. To follow the rules, you cannot use flashing skills to go directly out of the community.
StringBuilder response=new StringBuilder (); InputStream Is=connection.getinputstream (); BufferedReader br=new BufferedReader (New InputStreamReader (IS)); String str; while ((Str=br.readline ())!=null) { response.append (str); } Br.close (); Is.close ();
return response.tostring ();
Two. HttpGet Package
Source:
Static Publicstring HttpGet (string Url,map headers) {Try { //Open ConnectionURLConnection connection=Newurl (url). OpenConnection (); //set the request header if(headers!=NULL) {object[] objects=Headers.entryset (). ToArray (); for(Object o:objects) {string[] strings=o.tostring (). Split ("="); Connection.setrequestproperty (strings[0],strings[1]); } } //Get response InformationStringBuilder response=NewStringBuilder (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (Connection.getinputstream ())); String str; while((Str=br.readline ())! =NULL) {response.append (str); } br.close (); //return Results returnresponse.tostring (); } Catch(IOException e) {e.printstacktrace (); } return NULL; }
Call:
Map headers=New HashMap () headers.put ("Referer", "https://www.baidu.com/"); Headers.put ( "Cookie", "BIDUPSID=844B9321236FFD30C304AE4CCEE0602A; bd_upn=12314753 ") httpget (" https://www.baidu.com/", headers);
Three. Two major elements of Android network request
1. Apply for Network permissions: <uses-permission android:name= "Android.permission.INTERNET" ></uses-permission>;
2. Access the network in a child thread.
Android urlconnection Send GET request HttpGet Package