Android network communication and communication

Source: Internet
Author: User

Network operations are an essential part of the Android program for network communication. The Android platform has three network interfaces available: java.net. * (standard Java Interface), Org. apache HttpComponents interface and Android.net. * (Android Network Interface ). Of course, you can also use webkit in the browser for network access. The first two interfaces can be used for http and socket communication, and the last interface is mainly used to determine the network connection status of Android devices. Therefore, this section focuses on the first two interfaces. 1. java.net. * HttpURLConnection interface this interface provides networking-related classes, including stream and packet sockets, Internet protocol, and common HTTP processing. For example, create a URL and URLConnection/HttpURLConnection object, set connection parameters, connect to the server, write data to the server, and read data from the server. The following is an Http example of a common java.net package: HttpURLConnection is inherited from the URLConnection class, both of which are abstract classes. The object is mainly obtained through the openConnection method of the URL. The creation method is as follows: [html] URL url = new URL ("accessed url"); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); URL url = new URL ("accessed url"); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); you can set the request attributes using the following methods: [html] // set the conn of the input and output streams. setDoOutput (true); conn. setDoInput (true); // set the request method to post conn. setRequestMethod ("POST"); // The cached urlConn cannot be used for POST requests. setUseCaches (false); conn. connect (); Establish a connection // close the connection conn. disConnection (); // set the conn of the input and output streams. setDoOutput (true); conn. setDoInput (true); // set the request method to post conn. setRequestMethod ("POST"); // The cached urlConn cannot be used for POST requests. setUseCaches (false); conn. connect (); establish a link // close the connection conn. disConnection (); HttpURLConnection uses the GET method by default, as shown in the following code: [html] HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // use HttpURLConnection to open the connection. getResponseCode (); // get the connection status if (nRC = HttpURLConnection. HTTP_ OK) {InputStreamReader in = new InputStreamReader (urlConn. getInputStream (); // obtain the read content (Stream) // create BufferedReader buffer = new BufferedReader (in) for the output; String inputLine = null; // use a loop to read the obtained data while (inputLine = buffer. readLine ())! = Null) {// Add "\ n" next to each row to wrap resultData + = inputLine + "\ n" ;}// close InputStreamReader} in. close (); // close the http connection conn. disconnect (); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // use HttpURLConnection to open the connection int nRC = http. getResponseCode (); // get the connection status if (nRC = HttpURLConnection. HTTP_ OK) {InputStreamReader in = new InputStreamReader (urlConn. getInputStream (); // get the read content (Stream) // create a Buf for the output FeredReader BufferedReader buffer = new BufferedReader (in); String inputLine = null; // use a loop to read the obtained data while (inputLine = buffer. readLine ())! = Null) {// Add "\ n" next to each row to wrap resultData + = inputLine + "\ n" ;}// close InputStreamReader} in. close (); // close the http connection conn. disconnect (); if you need to use the POST method, you need to set setRequestMethod. The Code is as follows: [html] String httpUrl = "accessed url"; // String resultData = ""; URL url = null; try {// construct a URL object url = new URL (httpUrl);} catch (MalformedURLException e) {Log. e (DEBUG_TAG, "MalformedURLException");} if (url! = Null) {try {// use HttpURLConnection to open the connection HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // because this is a post request, it must be set to true conn. setDoOutput (true); conn. setDoInput (true); // set conn in POST mode. setRequestMethod ("POST"); // cache conn cannot be used for Post requests. setUseCaches (false); conn. setInstanceFollowRedirects (true); // configure the Content-type of the connection and set it to conn of application/x-www-form-urlencoded. setRequestProperty ("Conten T-Type "," application/x-www-form-urlencoded "); // connection, from postUrl. the current configuration of openConnection () must be completed before connect. // note that connection. getOutputStream implicitly performs connect. Conn. connect (); // DataOutputStream stream DataOutputStream out = new DataOutputStream (urlConn. getOutputStream (); // String content = "par =" + URLEncoder. encode ("ABCDEFG", "gb2312"); // write the content to be uploaded to the stream out. writeBytes (content); // refresh and close out. flush (); out. close (); String httpUrl = "accessed url"; // String resultData = ""; URL url = null; try {// construct a URL object url = new URL (httpUrl);} catch (MalformedURLExcept Ion e) {Log. e (DEBUG_TAG, "MalformedURLException");} if (url! = Null) {try {// use HttpURLConnection to open the connection HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // because this is a post request, it must be set to true conn. setDoOutput (true); conn. setDoInput (true); // set conn in POST mode. setRequestMethod ("POST"); // cache conn cannot be used for Post requests. setUseCaches (false); conn. setInstanceFollowRedirects (true); // configure the Content-type of the connection and set it to conn of application/x-www-form-urlencoded. setRequestProperty ("Conten T-Type "," application/x-www-form-urlencoded "); // connection, from postUrl. the current configuration of openConnection () must be completed before connect. // note that connection. getOutputStream implicitly performs connect. Conn. connect (); // DataOutputStream stream DataOutputStream out = new DataOutputStream (urlConn. getOutputStream (); // String content = "par =" + URLEncoder. encode ("ABCDEFG", "gb2312"); // write the content to be uploaded to the stream out. writeBytes (content); // refresh and close out. flush (); out. close (); you can also set the common attributes: [html] // set the common request attribute conn. setRequestProperty ("accept", "*/*"); conn. setRequestProperty ("connection", "Keep-Alive"); conn. setReque StProperty ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )"); // establish the actual connection // set the common request attribute conn. setRequestProperty ("accept", "*/*"); conn. setRequestProperty ("connection", "Keep-Alive"); conn. setRequestProperty ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )"); // establish the actual connection 2. Apache Http Client is an open-source project with more comprehensive functions. It provides efficient, up-to-date, and rich toolkit support for Http programming on the Client. It includes two request methods: get and post. The following example shows the get method: [html] StringBuilder stringBuilder = new StringBuilder (); HttpClient client = new DefaultHttpClient (); httpGet httpGet = new HttpGet (URL); try {HttpResponse response = client.exe cute (httpGet); StatusLine statusLine = response. getStatusLine (); int statusCode = statusLine. getStatusCode (); if (statusCode = 200) {HttpEntity entity = response. getEntity (); if (entity! = Null) {InputStream content = entity. getContent (); BufferedReader reader = new BufferedReader (new InputStreamReader (content); String line; while (line = reader. readLine ())! = Null) {stringBuilder. append (line) ;}} else {Log. e ("JSON", "Failed to download file") ;}} else {Log. e ("JSON", "Failed to download file") ;}} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return stringBuilder. toString (); StringBuilder stringBuilder = new StringBuilder (); HttpClient client = new DefaultHttpClient (); HttpGet httpGet = new HttpGet (URL); try {HttpResponse response = client.exe cute (httpGet); StatusLine statusLine = response. getStatusLine (); int statusCode = statusLine. getStatusCode (); if (statusCode = 200) {HttpEntity entity = response. getEntity (); if (entity! = Null) {InputStream content = entity. getContent (); BufferedReader reader = new BufferedReader (new InputStreamReader (content); String line; while (line = reader. readLine ())! = Null) {stringBuilder. append (line) ;}} else {Log. e ("JSON", "Failed to download file") ;}} else {Log. e ("JSON", "Failed to download file") ;}} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return stringBuilder. toString (); post method: When passing parameters using the post method, you need to use NameValuePair to save the parameters to be passed. In addition, you must set the character set used. The Code is as follows: [html] String httpUrl = "http: // 192.168.1.110: 8080/httppost"; // HttpPost connection object HttpPost httpRequest = new HttpPost (httpUrl ); // use NameValuePair to save the List of Post parameters to be passed <NameValuePair> params = new ArrayList <NameValuePair> (); // Add the params parameter to be passed. add (new BasicNameValuePair ("par", "regular"); // sets the character set HttpEntity httpentity = new UrlEncodedFormEntity (params, "gb2312"); // requests httpRequest httpR Equest. setEntity (httpentity); // get the default HttpClient httpclient = new response (); // get HttpResponse httpResponse = httpclient.exe cute (httpRequest); // HttpStatus. SC _ OK indicates that the connection is successful if (httpResponse. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {String strResult = EntityUtils. toString (httpResponse. getEntity (); mTextView. setText (strResult);} else {mTextView. setText ("request Error Incorrect! ") ;}} String httpUrl =" http: // 192.168.1.110: 8080/httppost "; // HttpPost connection object HttpPost httpRequest = new HttpPost (httpUrl ); // use NameValuePair to save the List of Post parameters to be passed <NameValuePair> params = new ArrayList <NameValuePair> (); // Add the params parameter to be passed. add (new BasicNameValuePair ("par", "tags"); // sets the character set HttpEntity httpentity = new UrlEncodedFormEntity (params, "gb2312"); // requests httpRequest. SetEntity (httpentity); // get the default HttpClient httpclient = new response (); // get HttpResponse httpResponse = httpclient.exe cute (httpRequest); // HttpStatus. SC _ OK indicates that the connection is successful if (httpResponse. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {String strResult = EntityUtils. toString (httpResponse. getEntity (); mTextView. setText (strResult);} else {mTextView. setText ("request error! ") ;}} HttpClient is actually some encapsulation of the methods provided by Java. The input and output stream operations in HttpURLConnection are uniformly encapsulated into HttpPost (HttpGet) and HttpResponse, this reduces the complexity of operations.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.