Android network programming using HttpClient for Get mode communication

Source: Internet
Author: User

In Android development, the Android SDK comes with Apache HttpClient, which is a perfect client. It provides full support for the HTTP protocol and can use HttpClient objects to perform HTTP GET and HTTP POST calls.

How HTTP Works:
1. Client (usually referred to as a browser, here refers to the program you write) to establish a connection with the server
2. After the connection is established, the client sends a request to the server
3. After the server receives the request, sends the response message to the client
4. Client disconnects from server

HttpClient General steps to use:
1. Instantiating a HttpClient object using the Defaulthttpclient class
2. Create a HttpGet or HttpPost object and pass the requested URL to the HttpGet or HttpPost object by constructing the method.
3. Call the Execute method to send an HTTP GET or HTTP POST request and return the HttpResponse object.
4. The response information is returned by the GetEntity method of the HttpResponse interface and processed accordingly.
Finally remember to add network permissions in the Androidmanifest.xml file
<uses-permission android:name= "Android.permission.INTERNET"/>

The following is an example of the data interface for an aggregated data air quality City Air PM2.5 Index, which demonstrates the use of httpclient for Get communication, a network connection through HttpClient, a HttpGet method for reading data, and an entity return value via HttpResponse.
Aggregated data air quality City Air PM2.5 index data Interface API documentation see: HTTP://WWW.JUHE.CN/DOCS/API/ID/33/AID/79
Sample request: http://web.juhe.cn:8080/environment/air/pm?city= city name &key= The Appkey value you applied for

Example: Httpclientgetdemo
Operating effect:


Code Listing:
Layout file: Activity_main.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "Vertical" tools:context= ". Mainactivity "> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_cont Ent "android:orientation=" horizontal "><textview android:layout_width=" Wrap_content "android:layout_he ight= "Wrap_content" android:layout_weight= "1" android:gravity= "center" android:text= "City:" Android:textsize= "23 SP "/><edittext android:id=" @+id/city "android:layout_width=" Wrap_content "Android:layout_heig ht= "Wrap_content" android:layout_weight= "3" android:inputtype= "text"/> "</LinearLayout> <butt         On android:id= "@+id/query" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:text= "Query" android:textsize= "23sp"/> <textviewandroid:id= "@+id/result" android:layout_width= "MATC H_parent "android:layout_height=" Match_parent "/></linearlayout>

Java source code file: Mainactivity.java

Package Com.rainsong.httpclientgetdemo;import Java.io.ioexception;import Java.net.urlencoder;import Java.util.arraylist;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.util.entityutils;import Android.os.bundle;import Android.os.strictmode;import Android.app.activity;import Android.view.menu;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;import Android.widget.toast;public class Mainactivity extends Activity {private static final String Juhe_url_environment_air_    PM = "HTTP://WEB.JUHE.CN:8080/ENVIRONMENT/AIR/PM";    private static final String Juhe_appkey = "The APPKEY value you applied for";    EditText et_city; Button Btn_query        TextView Tv_result;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Forces a network operation directly in the UI thread Strictmode.setthreadpolicy (new StrictMode.ThreadPolicy.Builder (). Detectdiskreads ().        Detectdiskwrites (). Detectnetwork (). Penaltylog (). build ()); Strictmode.setvmpolicy (New StrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobje        CTS (). Penaltylog (). Penaltydeath (). build ());        Setcontentview (R.layout.activity_main);        Et_city = (EditText) Findviewbyid (r.id.city);        Tv_result = (TextView) Findviewbyid (R.id.result);        Btn_query = (Button) Findviewbyid (r.id.query); Btn_query.setonclicklistener (New Onclicklistener () {public void OnClick (view view) {Tv_result.                SetText ("");                String City;                City = Et_city.gettext (). toString (); if (City.length () < 1) {                    Toast.maketext (Mainactivity.this, "Please enter city name", Toast.length_long). Show ();                Return                } arraylist<namevaluepair> headerlist = new arraylist<namevaluepair> (); Headerlist.add (New Basicnamevaluepair ("Content-type", "text/html;                Charset=utf-8 "));                String targeturl = juhe_url_environment_air_pm;                arraylist<namevaluepair> paramlist = new arraylist<namevaluepair> ();                Paramlist.add (New Basicnamevaluepair ("key", Juhe_appkey));                Paramlist.add (New Basicnamevaluepair ("Dtype", "JSON"));                                Paramlist.add (New Basicnamevaluepair ("City");                    for (int i = 0; i < paramlist.size (); i++) {Namevaluepair Nowpair = Paramlist.get (i);                    String value = Nowpair.getvalue (); try {value = Urlencoder.encode (Value, "UTF-8");                        } catch (Exception e) {} if (i = = 0) {                    TargetUrl + = ("?" + nowpair.getname () + "=" + value);                    } else {TargetUrl + = ("&" + nowpair.getname () + "=" + value);                }} httpget HttpRequest = new HttpGet (targeturl); try {for (int i = 0; i < headerlist.size (); i++) {Httprequest.addheader (hea                    Derlist.get (i). GetName (), Headerlist.get (i). GetValue ());                    } HttpClient HttpClient = new Defaulthttpclient ();                    HttpResponse HttpResponse = Httpclient.execute (HttpRequest); if (Httpresponse.getstatusline (). Getstatuscode () = = () {String strresult = entityutils.tostring ( HttpREsponse.getentity ());                    Tv_result.settext (strresult); } else {Toast.maketext (mainactivity.this, "Query failed", Toast.length_long                        ). Show ();                    Tv_result.settext ("");                }} catch (IOException e) {e.printstacktrace ();    }            }        }); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio        n Bar if it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; }}

Note: Network operations should not be done directly on the UI thread, blocking the UI and impacting the user experience. However, in order not to introduce other knowledge points, the focus is on httpclient network communication, which in this case forces the network operation directly in the UI thread. In the next article, you'll learn how to avoid network operations directly in the UI thread.


API Knowledge Points
public interface
HttpClient

Org.apache.http.client.HttpClient

Known Indirect subclasses
Abstracthttpclient, Androidhttpclient, defaulthttpclient

Class Overview
Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication , connection management, and other features. Thread Safety of HTTP clients depends on the implementation and configuration of the specific client.

Abstract HttpResponse Execute(Httpurirequest request)
Executes a request using the default context.

public class
defaulthttpclient
Extends Abstracthttpclient

Org.apache.http.impl.client.DefaultHttpClient

Class Overview
Default implementation of an HTTP client.

Public Constructor
Defaulthttpclient ()
Creates a new HTTP client.

public class
HttpGet
Extends Httprequestbase

Inherited Methods
From class Org.apache.http.client.methods.HttpRequestBase
From class Org.apache.http.message.AbstractHttpMessage
From class Java.lang.Object
From interface Org.apache.http.HttpMessage
From interface Org.apache.http.HttpRequest
From interface Org.apache.http.client.methods.AbortableHttpRequest
From interface Org.apache.http.client.methods.HttpUriRequest

Public constructors
HttpGet ()
HttpGet (URI Uri)
HttpGet (String URI)

abstract void AddHeader (string name, String value)
Adds a header to this message.

public interface
HttpResponse
Implements Httpmessage

Org.apache.http.HttpResponse

Class Overview
An HTTP response.

Abstract httpentity GetEntity ()
Obtains the message entity of this response, if any.

Abstract Statusline Getstatusline ()
Obtains the status line of this response.

public interface
Namevaluepair

Org.apache.http.NameValuePair

Known Indirect subclasses
Basicnamevaluepair

Class Overview
A Simple class encapsulating A attribute/value pair.

Public Methods
Abstract String GetName ()
Abstract String GetValue ()

public class
Basicnamevaluepair
Extends Object
Implements Cloneable Namevaluepair

Org.apache.http.message.BasicNameValuePair

Public constructors
Basicnamevaluepair (string name, String value)
Default Constructor taking a name and a value.



Android network programming using HttpClient for Get mode communication

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.