In Android application development, we often interact with the server to obtain or upload data, which requires the use of network requests, in general, the use of HTTP protocol to send and receive network data, and HTTP includes two ways of communication, namely:httpurlconnection and HttpClient.
code example: Https://git.oschina.net/ysx_xx/HttpText/tree/master
Let me briefly describe the use of both of these approaches:
First of all, to make a network request, we have to add network permissions to the app in two ways:
1. Open the androidmanifest.xml file, select permission, click Add :
choose the last one usespermission :
and then on the right . Name option to find Android.permission.INTERNET , Save
and then choose Androidmanifest.xml option, you can see
<uses-permissionandroid:name= "Android.permission.INTERNET"/>
2.The second approach is actually directlyandroidmanifestAdd the words above, if you are familiar with how to write.
--------------------------------------------------------------------------------------------------------------- ----------------------------------------
Well, here are the two ways to use the request
1. httpurlconnection:
First new URL object and incoming network address, then call the OpenConnection () method to get the HttpURLConnection instance, then set the method of HTTP request (Get/post), and then set the connection timeout, read timeout, message first, This can be written according to the actual situation, then use the getInputStream () method to get the input stream returned from the server, and read the contents, and finally call the disconnect () method to close.
Code:
New Thread (New Runnable () {@Overridepublic void run () {httpurlconnection connection = null;try {URL url = new URL ("/HTTP/ www.baidu.com/");//Call URL OpenConnection () method, get httpurlconnection instance connection = (HttpURLConnection) Url.openconnection ();//Set HTTP request method to get, general get for data from server, post for submit data to server Connection.setrequestmethod ("get");// Sets the number of milliseconds the connection time-out connection.setconnecttimeout (8000);//sets the number of milliseconds to read timeout connection.setreadtimeout (8000);// Gets the input stream returned by the server InputStream in = Connection.getinputstream ();//reads the input stream fetched BufferedReader reader = new BufferedReader (new InputStreamReader (in)); String response = "", Line;while ((line = Reader.readline ()) = null) {response + = line;} Get success, send success message Message message = new Message (); message.what = Success;message.obj = Response;mhandler.sendmessage ( message);} catch (Exception e) {//Send failure message Message message = new Message (); message.what = Faile;message.obj = "request Failed"; Mhandler.sendmessa GE (message); E.printstacktrace ();} finally {if (connection! = NULL) {//If connection is null, close it Connection.disConnect ();}}}). Start ();
The results are as follows:
The above is the introduction of the Get method, if you want to submit data to the server?
We can change the request mode to post and submit the parameters
For example:
Connection.setrequestmethod ("POST");D ataoutputstream out = new DataOutputStream (Connection.getoutputstream ()); O Ut.writebytes ("Username= Little Bear &password=123456");
2. Let's look at the usage of httpclient:
HttpClient is an interface where we create an instance of Defaulthttpclient, create an HttpGet object and pass in a network address, and then call the Execute () method of httpclient to send a GET request. Finally call HttpResponse's Getstatusline () Getstatuscode () method to get the status code returned by the server, if 200 indicates success
Code:
new Thread ( New Runnable () {@Overridepublic void run () {try {///= HttpClient is an interface, so create an instance with the Defaulthttpclient () method httpclient HttpClient = new Defaulthttpclient ();//Create HttpGet object and pass in the network address, and call HttpClient's Execute method to send GET request httpget HttpGet = new HttpGet ("http://www.baidu.com"); HttpResponse HttpResponse = Httpclient.execute (httpget);//First remove the status code returned by the server, if it is 200 indicates that the request response is successful, here you can determine the status code obtained// What determines success or failure if (Httpresponse.getstatusline (). Getstatuscode () = = 200) {//Request response succeeded, call GetEntity () Method gets the Httpentity instance and converts it to a string httpentity entity = httpresponse.getentity (); String response = entityutils.tostring (entity, "utf-8");//Get success, send success Message message = new Message (); message.what = Success;message.obj = response;mhandler.sendmessage (message);}} catch (Exception e) {//Send failure message Message message = new Message (); message.what = Faile;message.obj = "request Failed"; Mhandler.sendmessa GE (message); E.printstacktrace ();}}). Start ();
The effect is the same as httpurlconnection, here is not a lot of hair again. Here is the Post method for httpclient:
Key code:
HttpPost HttpPost = new HttpPost ("http://www.baidu.com"); list<namevaluepair> params = new arraylist<namevaluepair> ();p Arams.add (New Basicnamevaluepair ("username "," cubs ");p Arams.add (" Password "," 123456 ")); urlencodedformentity entity = new Urlencodedformentity (params, "utf-8"); httppost.setentity (entity); Httpclient.execute (HttpPost);
Full code:
Httpurlconnectiontext.java:
public class Httpurlconnectiontext extends Activity implements Onclicklistener {private final static int SUCCESS = 1;priva TE final static int faile = 0;private TextView result;private Button send;private loadingdialog loadingdialog;private Cont ext mcontext; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); InitData ();} private void InitData () {mcontext = This;result = (TextView) Findviewbyid (r.id.result); send = (Button) Findviewbyid (r.id. send); Send.setonclicklistener (this);} Private Handler Mhandler = new Handler () {public void Handlemessage (Message msg) {String response;if (loadingdialog! = null && loadingdialog.isshowing ()) {Loadingdialog.dismiss ();} Switch (msg.what) {Case success:response = msg.obj.toString (); Result.settext (response); Break;case Faile:response = Msg.obj.toString (); Result.settext (response); break;};}; @Overridepublic void OnClick (View v) {switch (V.getid ()) {case R.id.send:loadingdiAlog = new Loadingdialog (mcontext); Loadingdialog.setcancel (false); Loadingdialog.show (); Startsend (); break;}} private void Startsend () {New Thread (new Runnable () {@Overridepublic void run () {httpurlconnection connection = null;try { URL url = new URL ("http://www.baidu.com/");//Call URL of OpenConnection () method, get httpurlconnection instance connection = ( httpurlconnection) url.openconnection ();//Set HTTP request method to get, general get to get data from server, Post is to submit data to the server Connection.setrequestmethod ("GET");//Set the number of milliseconds for the connection timeout connection.setconnecttimeout (8000);// Sets the number of milliseconds to read timeout connection.setreadtimeout (8000);//Gets the input stream returned by the server InputStream in = Connection.getinputstream ();// Read BufferedReader reader = new BufferedReader (new InputStreamReader (in)) for the input stream fetched String response = "", Line;while ((line = Reader.readline ()) = null) {response + = line;} Get success, send success message Message message = new Message (); message.what = Success;message.obj = Response;mhandler.sendmessage ( message);} catch (Exception e) {//Send failure message Message message = new Message (); message.what = Faile;message.obj= "Request Failed"; mhandler.sendmessage (message); E.printstacktrace ();} finally {if (connection! = NULL) {//If connection is null, close it Connection.disconnect ();}}}). Start ();}}
Httpclienttext.java:
public class Httpclienttext extends Activity implements Onclicklistener {private final static int SUCCESS = 1;private Fina l static int faile = 0;private TextView result;private Button send;private loadingdialog loadingdialog;private Context mCo ntext; @Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); InitData ();} private void InitData () {mcontext = This;result = (TextView) Findviewbyid (r.id.result); send = (Button) Findviewbyid (r.id. send); Send.setonclicklistener (this);} Private Handler Mhandler = new Handler () {public void Handlemessage (Message msg) {String response;if (loadingdialog! = null && loadingdialog.isshowing ()) {Loadingdialog.dismiss ();} Switch (msg.what) {Case success:response = msg.obj.toString (); Result.settext (response); Break;case Faile:response = Msg.obj.toString (); Result.settext (response); break;};}; @Overridepublic void OnClick (View v) {switch (V.getid ()) {Case R.id.send:loadingdialog =New Loadingdialog (Mcontext); Loadingdialog.setcancel (false); Loadingdialog.show (); Startsend (); break;}} private void Startsend () {New Thread (new Runnable () {@Overridepublic void run () {try {//) because HttpClient is an interface, So create an instance with the Defaulthttpclient () method HttpClient httpClient = new Defaulthttpclient ();//Create a HttpGet object and pass in the network address, and call HttpClient's Execute method to send a GET request httpget HttpGet = new HttpGet ("http://www.baidu.com"); HttpResponse HttpResponse = Httpclient.execute (httpget);//First remove the status code returned by the server, if it is 200 indicates that the request response is successful, here you can determine the status code obtained// What determines success or failure if (Httpresponse.getstatusline (). Getstatuscode () = = 200) {//Request response succeeded, call GetEntity () Method gets the Httpentity instance and converts it to a string httpentity entity = httpresponse.getentity (); String response = entityutils.tostring (entity, "utf-8");//Get success, send success Message message = new Message (); message.what = Success;message.obj = response;mhandler.sendmessage (message);}} catch (Exception e) {//Send failure message Message message = new Message (); message.what = Faile;message.obj = "request Failed"; Mhandler.sendmessa GE (message); E.printstacktrace ();}}). Start ();}}
Welcome to bear Public Number Oh ^_^ Sync update ...
Number: SMILE_KLXX
Android Network Request method