Android Network Programming: HttpClient for Get-based communication, androidhttpclient

Source: Internet
Author: User

Android Network Programming: HttpClient for Get-based communication, androidhttpclient
In Android development, the Android SDK comes with Apache HttpClient, which is a complete client. It provides comprehensive support for the HTTP protocol. You can use HttpClient objects to execute http get and http post calls.

How HTTP works:
1. The client (generally a browser, which is a self-written Program) establishes a connection with the server.
2. After the connection is established, the client sends a request to the server
3. the server sends a response to the client after receiving the request.
4. Disconnect the client from the server

General steps for HttpClient:
1. Use the DefaultHttpClient class to instantiate the HttpClient object
2. Create an HttpGet or HttpPost object and pass in the http get or HttpPost object through the construction method of the requested URL.
3. Call the execute method to send an http get or http post request and return the HttpResponse object.
4. Return the response information through the getEntity method of the HttpResponse interface and perform corresponding processing.
Remember to add network permissions in the AndroidManifest. xml file.
<Uses-permission android: name = "android. permission. INTERNET"/>

The following uses the aggregated data Air Quality City Air PM2.5 index data interface as an example to demonstrate how to use HttpClient for Get-based communication, establish a network connection through HttpClient, and use HttpGet to read data, and get the return value of Entity through 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
Request example: http://web.juhe.cn: 8080/environment/air/pm? City = city name & key = The APPKEY value you applied

Instance: HttpClientGetDemo
Running effect:


Code List:
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: orientation = "vertical" tools: context = ". mainActivity "> <LinearLayout android: layout_width =" match_parent "android: layout_height =" wrap_content "android: orientation =" horizontal "> <TextView android: layout_width =" wrap_content "android: layout_height = "wrap_content" android: layout_weight = "1" android: gravity = "center" android: text = "City:" android: textSize = "23sp"/> <EditText android: id = "@ + id/city" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_weight = "3" android: inputType = "text"/> "</LinearLayout> <Button 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 = "match_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_ENVI RONMENT_AIR_PM = "http://web.juhe.cn: 8080/environment/air/pm"; private static final String JUHE_APPKEY = "Your applied APPKEY value"; EditText et_city; Button btn_query; TextView TV _result; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // force the network operation StrictMode directly in the UI thread. setThreadPolicy (new StrictMode. threadPolicy. builder (). detectDiskReads (). detectDiskWrites (). de TectNetwork (). penaltyLog (). build (); StrictMode. setVmPolicy (new StrictMode. vmPolicy. builder (). detectLeakedSqlLiteObjects (). detectLeakedClosableObjects (). 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.setOnClickListen Er (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, "enter the 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", 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 

Note: network operations should not be performed directly in the UI thread, which will block the UI and affect the user experience. However, in order not to introduce other knowledge points, the focus is concentrated on HttpClient network communication. In this example, network operations are enforced directly in the UI thread. In the next article, we will introduce how to avoid network operations in the UI thread.


API knowledge point
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 acthttpclient

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 an 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.



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.