Android Network Communication (HttpUrlConnection and HttpClient)

Source: Internet
Author: User
Tags webdate

Preface: There are two network communication methods for Android: Socket or HTTP. Today, we will explain in detail the network communication implemented by HTTP. HTTP includes two programming methods:

1) HttpUrlConnection;

2) HttpClient;

Well, Let's explain it directly. Of course, there will be some other knowledge about Android network communication before, and we should also understand it.


1. How to get the network status

1) key code in MainActivity. java

// Network management class, which can determine whether the Internet can be accessed and the network type ConnectivityManager cm = (ConnectivityManager) getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo info = cm. getActiveNetworkInfo (); if (info! = Null) {Toast. makeText (MainActivity. this, "network connection is normal" + info. getTypeName (), Toast. LENGTH_SHORT ). show ();} else {Toast. makeText (MainActivity. this, "not connected", Toast. LENGTH_SHORT ). show ();}

2) Note: you must add this permission to the master configuration file.

It is the sibling tag of the application:

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

3) OK. Let's take a look at the Internet access status and type of our devices:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1031215X9-0.jpg "title =" Capture. JPG "/>


Ii. Use a URL to access the webpage source code

1) MainActivity. java:

Package com. example. l0903_urldata; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java.net. malformedURLException; import java.net. URL; import android. app. activity; import android. OS. bundle;/*** webpage source code * @ author asus **/public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); try {// source code for accessing Baidu's html file InputStream is = new URL (" http://www.baidu.com "). OpenStream (); // The encapsulated stream for reading data BufferedReader br = new BufferedReader (new InputStreamReader (is); // str is used to read a row of data String str = null; // StringBuffer is used to store reverse data StringBuffer sb = new StringBuffer (); while (str = br. readLine ())! = Null) {sb. append (str);} System. out. println (sb. toString ();} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}

2) Note: you must add the following permissions to the master configuration file for network operations:

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


3. Simple use of the WebView Control

Package com. example. l0903_webview; import android. app. activity; import android. OS. bundle; import android. webkit. webView;/*** is actually a browser control. * @ author asus **/public class MainActivity extends Activity {private WebView wv; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); wv = (WebView) findViewById (R. id. webView1); // WebView control method. loadUrl is used to load the specified network address wv. loadUrl ("http://www.baidu.com ");}}

Running effect:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/10312114G-1.jpg "title =" Capture. JPG "/>


4. Use HttpUrlConnection to write Android Network Communication

1. First, build a server:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/10312123G-2.jpg "title =" Capture. JPG "/>


650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1031211231-3.jpg "title =" Capture. JPG "/>


2. The following is about the client:

(1) get:

MainActivity. java:

Package com. example. l0903_httpurlcnectionget; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. editTe Xt; import android. widget. TextView;/*** Get server data using the Get Method * directly in the address "? + The key value + value method is used to display the * passed parameters directly. Unsafe * @ author asus **/public class MainActivity extends Activity {private HttpURLConnection conn; private URL url; private InputStream is; private TextView TV; private EditText et; private String name; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); TV = (TextView) findViewById (R. id. textView1); et = (EditText) findViewById (R. id. editText1); findViewById (R. id. button1 ). setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {name = et. getText (). toString (); // defines the address of the accessed server. 10.0.2.2 is the address of the local server accessed by Android String urlDate =" http://10.0.2.2:8080/My_Service/webdate.jsp?name= "+ Name; try {// encapsulate the url of the Access Server = new URL (urlDate); try {// open the connection to the server conn = (HttpURLConnection) url. openConnection (); // connect to the server conn. connect ();/** process of reading server data ** // obtain the input stream is = conn. getInputStream (); // create a packaging stream BufferedReader br = new BufferedReader (new InputStreamReader (is); // define the String type for storing single row data String line = null; // create a StringBuffer object to store all data. StringBuffer sb = new StringBuffer (); while (line = br. readLine ())! = Null) {sb. append (line);} // use TextView to display the received server data TV. setText (sb. toString (); System. out. println (sb. toString ();} catch (IOException e) {e. printStackTrace () ;}} catch (MalformedURLException e) {e. printStackTrace ();}}});}}

The permission is the second permission on the same page. All Network-related operations need to be added)

Running effect:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1031214955-4.jpg "title =" Capture. JPG "/>


2) post-based security)

MainActivity. java

Package com. example. l0903_httpurlconectionpost; import java. io. bufferedReader; import java. io. dataOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import java.net. URLEncoder; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. editText; import android. widget. textView;/*** pass the parameter * Security * @ author asus **/public class MainActivity extends Activity {private HttpURLConnection conn; private URL url; private InputStream is through the Post method; private OutputStream OS; private EditText et; private TextView TV; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); et = (EditText) findViewById (R. id. editText1); TV = (TextView) findViewById (R. id. TV); findViewById (R. id. button1 ). setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub String urlDate =" http://10.0.2.2:8080/My_Service/webdate.jsp "; Try {url = new URL (urlDate); try {// open the server conn = (HttpURLConnection) url. openConnection (); // set the input/output stream conn. setDoOutput (true); conn. setDoInput (true); // set the request method to Post conn. setRequestMethod ("POST"); // If the Post method cannot cache data, you must manually set the value to false conn. setUseCaches (false); // connect to the database conn. connect ();/** write parameter **/OS = conn. getOutputStream (); // encapsulate the data written to the server here is the parameter to be passed) DataOutputStream dos = new DataOutputStream (OS); // write method: name is ke The value of y cannot be changed, the encoding method can use Chinese dos to use UTF-8. writeBytes ("name =" + URLEncoder. encode (et. getText (). toString (), "UTF-8"); // close the outer packing flow dos. close ();/** read server data **/is = conn. getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (is); String line = null; StringBuffer sb = new StringBuffer (); while (line = br. readLine ())! = Null) {sb. append (line);} TV. setText (sb. toString (); System. out. println (sb. toString ();} catch (IOException e) {e. printStackTrace () ;}} catch (MalformedURLException e) {e. printStackTrace ();}}});}}



5. Use HttpClient to write Android Network Communication

1. servers are the same as above;

2. get:

package com.example.l0903_http_get;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.app.Activity;import android.os.Bundle;public class MainActivity extends Activity {    private HttpGet get;    private HttpClient cliet;    private HttpResponse response;    private HttpEntity entity;    private InputStream is;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        get=new HttpGet("http://10.0.2.2:8080/My_Service/webdate.jsp?name=ooooooo");        cliet=new DefaultHttpClient();        try {            response=cliet.execute(get);            entity=response.getEntity();            is=entity.getContent();            BufferedReader br=new BufferedReader(new InputStreamReader(is));            String line=null;            StringBuffer sb=new StringBuffer();            while((line=br.readLine())!=null){                sb.append(line);            }            System.out.println(sb.toString());        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }                                                   }}


3. post:

Package com. example. l0903_http_post; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. unsupportedEncodingException; import java. util. arrayList; import java. util. list; import org. apache. http. httpEntity; import org. apache. http. httpResponse; import org. apache. http. client. clientProtocolException; import org. apache. http. client. httpClient; import org. apache. http. client. entity. urlEncodedFormEntity; import org. apache. http. client. methods. httpPost; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. message. basicNameValuePair; import android. app. activity; import android. OS. bundle; public class MainActivity extends Activity {// create a request object private HttpPost post; // create a client object private HttpClient cliet; // create a request object private HttpResponse response; // private UrlEncodedFormEntity urlEntity; // create the private HttpEntity entity object for receiving returned data; // create the stream object private InputStream is; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // the address of the request for packaging post = new HttpPost (" http://10.0.2.2:8080/My_Service/webdate.jsp "); // Create the Default Client object cliet = new DefaultHttpClient (); // use list to encapsulate the parameter List <BasicNameValuePair> pairs = new ArrayList <BasicNameValuePair> (); pairs. add (new BasicNameValuePair ("name", "llllllllllll"); try {// use UrlEncodedFormEntity to encapsulate the List object urlEntity = new UrlEncodedFormEntity (pairs ); // sets the Entity post. setEntity (urlEntity); try {// The client starts to send the request responseclientcliet.exe cute (post) to the specified URL; // obtain the requested Entity entity = response. GetEntity (); is = entity. getContent (); // The following process reads data: BufferedReader br = new BufferedReader (new InputStreamReader (is); String line = null; StringBuffer sb = new StringBuffer (); while (line = br. readLine ())! = Null) {sb. append (line);} System. out. println (sb. toString ();} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}} catch (UnsupportedEncodingException e) {e. printStackTrace ();}}}


4. Implement the combination of HttpClient communication and AsyncTask asynchronous mechanism:

Package com. example. l0903_http_asynctask_get; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import org. apache. http. httpEntity; import org. apache. http. httpResponse; import org. apache. http. client. clientProtocolException; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. Client. defaultHttpClient; import android. app. activity; import android. app. progressDialog; import android. OS. asyncTask; import android. OS. bundle; import android. widget. textView;/***** @ author asus **/public class MainActivity extends Activity {private TextView TV; // create a request object private HttpGet httpGet; // create the client object private HttpClient httpClient; // send the request object private HttpResponse httpResponse; // receive the returned data privat E HttpEntity httpEntity; // create a stream private InputStream in; private ProgressDialog pd; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); TV = (TextView) findViewById (R. id. TV); AsyncTask <String, Void, String> asyncTask = new AsyncTask <String, Void, String> () {@ Override protected String doInString... params) {Stri Ng urlstr = params [0]; httpGet = new HttpGet (urlstr); httpClient = new DefaultHttpClient (); try {// send the request httpResponse = httpClient.exe cute (httpGet) to the server ); httpEntity = httpResponse. getEntity (); in = httpEntity. getContent (); BufferedReader br = new BufferedReader (new InputStreamReader (in); String line = null; StringBuffer sb = new StringBuffer (); while (line = br. readLine ())! = Null) {sb. append (line);} System. out. println (sb. toString (); return sb. toString ();} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return null;} @ Override protected void onPostExecute (String result) {if (result! = Null) {TV. setText (result); pd. dismiss (); // remove dialog} super. onPostExecute (result) ;}}; pd = ProgressDialog. show (this, "Please wait... "," Requesting data "); asyncTask.exe cute (" http://10.0.2.2:8080/My_Service/webdate.jsp?name=haha&age=hh ");}}

Running effect:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1031214596-5.jpg "title =" Capture. JPG "/>


This article is from the MySpace blog, please be sure to keep this source http://wangzhaoli.blog.51cto.com/7607113/1288000

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.