Android HTTP-based network communication --- HttpURLConnection

Source: Internet
Author: User

Android's network communication mechanism is undoubtedly used to deal with the network. There are two communication methods: Http and Socket. There is no difference between Socket communication methods and Java. This is not the focus of our speech today. The focus is on the http Communication Method. Let's take a look at her face.

I. Classification of Http Communication Methods

1) HttpURLConnection

2) The HttpClient method will be repeated tomorrow)

Ii. Http request methods

There are two methods: post method and get method. The main differences are as follows:

Similarities: both of them can send data to the server, and the server closes the connection after returning the corresponding data according to the request;

Differences: 1) the size of data transmitted by the get method is small and cannot exceed 2 kb, while that transmitted by the post method is large, which is generally unrestricted.

2) The parameter values passed by the post method are not displayed on the URL, while those passed by get are displayed on the URL.

3) high post security and low get security

3. HttpURLConnection Request Method -- Get

Before the operation, we should build a server and write a file on the server side. The file function I wrote here is that when the passed parameters are not empty, concatenates the output string. The specific file is as follows:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><%    String a = request.getParameter("a");    String b = request.getParameter("b");    if(a!=null&&b!=null){    out.println(a + b);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         }else {        out.print("error");    }%>

◆ Steps:

You can add a button on the main interface. The following operations are generated when you click the button to trigger the event. To put it bluntly, put the following operations into the button's listening event, and then click OK.

1) define a string with the value of server address. Because the get method is used to request data, the parameter transmission method is: URL address? Key = Value &... The keys here correspond to the Keys received on the server.

// The server address. Note that the parameter transfer method must be directly written after the URL. Format :? Key = Value & Key = value String urlStr = "http: // 222.27.166.10: 8080/MyServer/youcan. jsp? A = Hello & B = word ";

2) create a URL object and convert the preceding server address string to a URL address

URL url = new URL (urlStr); // convert the server address string to the URL format

3) create an HttpURLConnection object and open the URL through openConnection of the URL object. Note that only the URL is opened at this time.

HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // open the url

4) connect to the server through the connect Method of the HttpURLConnection object, then you can deal with the server.

Conn. connect (); // link

5) use the getInputStream method of HttpURLConnection to obtain the input stream and read the data returned by the server.

In = conn. getInputStream (); // get the input stream BufferedReader br = new BufferedReader (new InputStreamReader (in); // get the input stream's packaging stream String str = null; // stores the row of read data StringBuffer sb = new StringBuffer (); // concatenates string data while (str = br. readLine ())! = Null) {// judge whether sb has been read. append (str); // if it is not completed, it is spliced} System. out. println (sb. toString (); // The value returned by the server

6) particularly important: to add network access permissions to the Manifest. xml file, all network communication operations on android require permissions.

<uses-permission android:name="android.permission.INTERNET" />

◆ Result: the string splicing style is output in the background.

01-07 15:55:54.622: INFO/System.out(618): Helloword

Iv. HttpURLConnection Request Method-Post

Here we also use the above Server File to return String concatenation.

◆ Steps:

1) define a string with the value of the server address. Because the post method is used to request data, parameters cannot be directly written after the URL. Note.

// Server address. Note that the post transmission method cannot directly transmit the parameter String urldata = "http: // 222.27.166.10: 8080/MyServer/youcan. jsp ";

2) create a URL object and convert the preceding server address string to a URL address

url = new URL(urldata);

3) create an HttpURLConnection object and open the URL through openConnection of the URL object. Note that only the URL is opened at this time.

// Open the url conn = (HttpURLConnection) url. openConnection ();

4) set related properties of the HttpURLConnection object, as shown below:

// Set the post method to not cache data conn. setUseCaches (false); // set the parameter passing method to postconn. setRequestMethod ("POST"); // sets the output stream conn. setDoOutput (true); // set the conn of the input stream. setDoInput (true );

5) connect to the server through the connect Method of the HttpURLConnection object, then you can deal with the server.

// Start to connect to conn. connect ();

6) use the getOutputStream method of the HttpURLConnection object to get the output stream and write the passed parameters to it.

// Get the output stream, write the parameter to the Server out = conn. getOutputStream (); DataOutputStream dos = new DataOutputStream (out); // The method for passing parameters. URLEncoder writes data through the output stream. the encode parameter is "key-corresponding value" and "encoding method" dos. writeBytes ("a =" + URLEncoder. encode ("quanquan", "UTF-8"); DataOutputStream dos1 = new DataOutputStream (out); // The method for passing parameters. URLEncoder writes data through the output stream. the encode parameter is "key-corresponding value" and "encoding method" dos1.writeBytes ("B =" + URLEncoder. encode ("quanquan", "UTF-8 "));

7) use the getInputStream method of the HttpURLConnection object to obtain the input stream and read the data returned by the server.

// Obtain the input stream and the returned data in = conn. getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (in); // read String line = null for returned data; StringBuffer sb = new StringBuffer (); while (line = br. readLine ())! = Null) {sb. append (line);} System. out. println (sb. toString ());

◆ Result: the result is output on the console.

01-07 15:55:54.622: INFO/System.out(618): quanquanquanquan


There are many other Android communication methods. People who like these methods may have different ways of communication. You can choose which one you like to use. Here I am not talking about it very comprehensively. Thank you for your understanding. 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/102G4BP-0.gif "/>


This article is from the "Schindler" blog, please be sure to keep this source http://cinderella7.blog.51cto.com/7607653/1289581

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.