Android [intermediate tutorial] Chapter 9 network data processing: httpclient

Source: Internet
Author: User
Tags call back

This chapter mainly introduces the transmission and processing of network data. I believe many readers hope that their applications can interact with data on the network, such as Weibo and forums, here we need to learn how to process network transmission and returned data. First, the network transmission parameters include post and get protocols, which should be known by those who have done web pages or have learned. each form on the webpage has a <form action = "XXX" method = "Post"> parameter. Here, method is the protocol used to submit the form parameters. Of course, there are more than two protocols, there is also the File Upload protocol, which we will talk about later. Today we will be familiar with the post and get protocols in Android. First, we provide an httpconnectionutil. java helper class, which encapsulates post and get

Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. unsupportedencodingexception; import java.net. urlencoder; import Java. util. arraylist; import Java. util. list; import Java. util. map; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. httpstatus; import Org. apache. HTTP. namevaluepair; import Org. apache. HTTP. client. clientprotocolexception; import or G. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. entity. urlencodedformentity; import Org. apache. HTTP. client. methods. httpget; import Org. apache. HTTP. client. methods. httppost; import Org. apache. HTTP. client. methods. httpurirequest; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. message. basicnamevaluepair; import android. OS. handler; import android. util. log; Public clas S httpconnectionutil {public static Enum httpmethod {Get, post}/*** asynchronous connection ** @ Param URL * @ Param Method * HTTP method, post and get * @ Param callback * callback methods, which are returned to the page or other data */Public void asyncconnect (final string URL, final httpmethod method, final httpconnectioncallback callback) {asyncconnect (URL, null, method, callback);}/*** synchronous method ** @ Param URL * @ Param Method * HTTP method, post and get * @ Param callback * back Call method, return to the page or other data */Public void syncconnect (final string URL, final httpmethod method, final httpconnectioncallback callback) {syncconnect (URL, null, method, callback);}/*** asynchronous parameter method ** @ Param URL * @ Param Params * post or get parameter * @ Param Method * method, post or get * @ Param callback * callback Method */Public void asyncconnect (final string URL, final map <string, string> Params, final httpmethod, final httpc Onnectioncallback callback) {handler = new handler (); runnable = new runnable () {public void run () {syncconnect (URL, Params, method, callback );}}; handler. post (runnable);}/*** synchronous belt parameter method ** @ Param URL * @ Param Params * post or get parameter * @ Param Method * method, post or get * @ Param callback * callback Method */Public void syncconnect (final string URL, final map <string, string> Params, final httpmethod m Ethod, final httpconnectioncallback callback) {string JSON = NULL; bufferedreader = NULL; try {httpclient client = new defaulthttpclient (); httpurirequest request = getrequest (URL, Params, method ); httpresponse response = client.exe cute (request); If (response. getstatusline (). getstatuscode () = httpstatus. SC _ OK) {reader = new bufferedreader (New inputstreamreader (response. getentity (). getcontent (); s Tringbuilder sb = new stringbuilder (); For (string S = reader. Readline (); s! = NULL; S = reader. readline () {sb. append (s);} JSON = sb. tostring () ;}} catch (clientprotocolexception e) {log. E ("httpconnectionutil", E. getmessage (), e);} catch (ioexception e) {log. E ("httpconnectionutil", E. getmessage (), e);} finally {try {If (reader! = NULL) {reader. close () ;}} catch (ioexception e) {// ignore metric+callback.exe cute (JSON) ;}/ *** the post parameter is different from the get parameter, and post is passed implicitly, get is to explicitly pass the ** @ Param URL * @ Param Params * parameter * @ Param Method * @ return */private httpurirequest getrequest (string URL, Map <string, string> Params, httpmethod method) {If (method. equals (httpmethod. post) {list <namevaluepair> listparams = new arraylist <namevaluepair> (); If (Param S! = NULL) {for (string name: Params. keyset () {listparams. add (New basicnamevaluepair (name, Params. get (name) ;}}try {urlencodedformentity entity = new urlencodedformentity (listparams); httppost request = new httppost (URL); Request. setentity (entity); return request;} catch (unsupportedencodingexception e) {// shocould not come here, ignore me. throw new Java. lang. runtimeexception (E. getmessage (), e) ;}} else {if (URL. indexof ("? ") <0) {URL + = "? ";} If (Params! = NULL) {for (string name: Params. keyset () {try {URL + = "&" + name + "=" + urlencoder. encode (Params. get (name), "UTF-8");} catch (unsupportedencodingexception e) {e. printstacktrace () ;}} httpget request = new httpget (URL); return request ;}} /*** callback interface ** @ author administrator **/public interface httpconnectioncallback {/*** call back method will be execute after the HTTP request return. ** @ Param response * the response of HTTP request. the value will be null if * any error occur. */void execute (string response );}}

This class is also seen on the Internet. It is quite convenient to use. I hope readers can learn how to use it. In fact, for Java, they can define their own packages for some useful classes or methods, put them in. You only need to call them in the main program next time. This is also an important object-oriented method.

Here, I didn't define a line in one line, and all the methods in httpclient are used.

Next, we will use this class for Android applications.

Main. XML (template file)

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <edittext Android: layout_width = "match_parent" Android: layout_height = "wrap_content" Android: Id = "@ + ID/http_edit" Android: text = "http: // "> <requestfocus> </edittext> <relativelayout Android: layout_width =" match_parent "and Roid: layout_height = "wrap_content" Android: Id = "@ + ID/relativelayout1"> <button Android: text = "cancel" Android: layout_width = "wrap_content" Android: id = "@ + ID/http_cancal" Android: layout_height = "wrap_content" Android: layout_alignparenttop = "true" Android: layout_alignparentright = "true"> </button> <button Android: TEXT = "OK" Android: layout_width = "wrap_content" Android: Id = "@ + ID/http_ OK" Android: layout_height = "wrap_conte NT "Android: layout_alignparenttop =" true "Android: layout_toleftof =" @ + ID/http_cancal "Android: layout_marginright =" 14dp "> </button> </relativelayout> <scrollview Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <textview Android: Id = "@ + ID/http_text" Android: text = "textview" Android: textappearance = "? Android: ATTR/textappearancesmall "Android: layout_height =" match_parent "Android: layout_width =" match_parent "> </textview> </scrollview> </linearlayout>

Then there is the Java code of the main actitiv.

Import android. app. activity; import android. OS. bundle; import android. text. HTML; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. textview; import COM. kang. HTTP. httpconnectionutil; import COM. kang. HTTP. httpconnectionutil. httpconnectioncallback; import COM. kang. HTTP. httpconnectionutil. httpmethod; public class Httpclientdemo extends activity {private button OK _btn; private button cancal_btn; private edittext edit_text; private textview text; @ overrideprotected void oncreate (bundle savedinstancestate) {// todo auto-generated method stubsuper. oncreate (savedinstancestate); setcontentview (R. layout. http_client); // click the OK button OK _btn = (button) findviewbyid (R. id. http_ OK); OK _btn.setonclicklistener (New clickevent (); // cancel the button can Cal_btn = (button) findviewbyid (R. id. http_cancal); cancal_btn.setonclicklistener (New clickevent (); // text edit box edit_text = (edittext) findviewbyid (R. id. http_edit); // text box text = (textview) findviewbyid (R. id. http_text);} // custom button click method public class clickevent implements onclicklistener {@ overridepublic void onclick (view v) {Switch (v. GETID () {case R. id. http_ OK: // URL string url = edit_text.gettext (). tostring (). trim (); If (! URL. Equals ("http ://")&&! URL. equals ("") {// custom class, encapsulates the get/POST method, and also encapsulates the synchronous and asynchronous Methods httpconnectionutil conn = new httpconnectionutil (); Conn. asyncconnect (URL, httpmethod. get, new httpconnectioncallback () {@ overridepublic void execute (string response) {text. settext (HTML. fromhtml (response) ;}}) ;}break; case R. id. http_cancal: edit_text.settext ("http: //"); break ;}}}}

In the clickevent class, we use the custom httpconnectionutil class in The onclick method. Don't rush to run it. Next, we have another step. The most important thing is the increase of permissions, to access the network, you must have the permission to access the network. add <uses-Permission Android: Name = "android. permission. internet "> </uses-Permission>: If you want to add a domain name, do not ask me, Baidu or Google, now you can run it. See if the figure is the same as mine.

You must be wondering, how can there be other code? The source code is extracted here. OK. This chapter is complete. We will display the MySQL database + PHP + android in the next chapter. I believe this will be a chapter of interest to many readers. Thank you.

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.