Android Development-Network communication 2

Source: Internet
Author: User
Tags response code

Three methods of communication were debugged: HttpClient, Asynchttpclient and volley.

HttpClient test code [1]:

 Public classHttputil { Public Static voidSendrequestwithhttpclient (final String address, final list<namevaluepair>params, final Httpcallbacklistener listener) {        NewThread (NewRunnable () {@Override Public voidrun () {Try{httppost HttpPost=NewHttpPost (address); HttpClient HttpClient=Newdefaulthttpclient ();                    Urlencodedformentity postentity; Postentity=NewUrlencodedformentity (params,"Utf-8");                    Httppost.setentity (postentity); HttpResponse HttpResponse=Httpclient.execute (HttpPost); if(Httpresponse.getstatusline (). Getstatuscode () = = $) {httpentity reentity=httpresponse.getentity (); String Reposnse= Entityutils.tostring (reentity,"Utf-8"); if(Listener! =NULL) {listener.onfinish (reposnse); }                    }                                    }Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace ();    }}). Start (); }}
String Usertel =Et_usertel.gettext (). toString (). Trim (); String Password=Et_password.gettext (). toString (). Trim (); String Url_login="http://192.168.1.102:8999/weixin/index.php/Home/Index/test"; List<NameValuePair>params=NewArraylist<namevaluepair>();params. Add (NewBasicnamevaluepair ("Usertel", Usertel));params. Add (NewBasicnamevaluepair ("Password", password)); Httputil.sendrequestwithhttpclient (Url_login,params,NewHttpcallbacklistener () {@Override Public voidonfinish (String response) {Parsejsonwithjsonobject (response); } @Override Public voidOnError (Exception e) {e.printstacktrace (); }});
Private voidParsejsonwithjsonobject (String jsondata) {Try{Jsonarray Jsonarray=NewJsonarray (Jsondata); LOG.D ("Com.dlwz.playfootball","In parsejsonwithjsonobject");  for(intI=0; I<jsonarray.length (); i++) {Jsonobject jsonobject=Jsonarray.getjsonobject (i); String name= Jsonobject.getstring ("Usertel"); String Password= Jsonobject.getstring ("Password"); LOG.D ("Com.dlwz.playfootball","Name:"+name+", Password:"+password);            Dialog.dismiss (); StartActivity (NewIntent (loginactivity. This, Mainactivity.class)); }    } Catch(Exception e) {e.printstacktrace (); }}

Asynchttpclient test code [2]:

Requestparamsparams=Newrequestparams ();params. put ("username", email);params. put ("Password", password); Asynchttpclient Client=Newasynchttpclient (); client.Get("Http://192.168.1.102:8081/useraccount/login/dologin",params,NewAsynchttpresponsehandler () {//When the response returned by REST have Http response code ' $ '@Override Public voidonsuccess (String response) {//Hide Progress Dialogprgdialog.hide (); Try {              //JSON ObjectJsonobject obj =NewJsonobject (response); //When the JSON response have status Boolean value assigned with True             if(Obj.getboolean ("Status") {toast.maketext (Getapplicationcontext ()),"You are successfully logged in!", Toast.length_long). Show (); //Navigate to Home screennavigatetohomeactivity (); }              //Else Display error message             Else{errormsg.settext (obj.getstring ("error_msg")); Toast.maketext (Getapplicationcontext (), Obj.getstring ("error_msg"), Toast.length_long). Show (); }     } Catch(jsonexception e) {//TODO auto-generated Catch blockToast.maketext (Getapplicationcontext (),"Error occured [Server ' s JSON response might be invalid]!", Toast.length_long). Show ();     E.printstacktrace (); } } //When the response returned by REST have Http response code other than ' $ '@Override Public voidOnFailure (intStatusCode, throwable error, String content) {     //Hide Progress Dialogprgdialog.hide (); //When the Http response code is ' 404 '     if(StatusCode = =404) {Toast.maketext (Getapplicationcontext (),"requested resource not found", Toast.length_long). Show (); }      //When the Http response code is '     Else if(StatusCode = = -) {Toast.maketext (Getapplicationcontext (),"Something went wrong at server end", Toast.length_long). Show (); }      //When the Http response code other than 404,     Else{Toast.maketext (Getapplicationcontext (),"unexpected Error occcured! [Most common error:device might not being connected to the Internet or remote server is not up and running]", Toast.length_long). Show (); } }});

Volley post test code [3]:

Requestqueue Mqueue = Volley.newrequestqueue ( This); Stringrequest stringrequest=NewStringrequest (Request.Method.POST,"http://192.168.1.102:8999/weixin/index.php/Home/Index/test",                                NewResponse.listener<string>() {@Override Public voidOnresponse (String response) {LOG.D ("Tag-onresponse", response); }        }, NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {LOG.E ("Tag-onerrorresponse", Error.getmessage (), error); }}) {@OverrideprotectedMap<string, string>Getparams () throws Authfailureerror {Map<string, string> map =NewHashmap<string, string>(); Map.put ("username","[email protected]"); Map.put ("Password","123456"); returnmap; }};mqueue.add (stringrequest);

Resources:

1, class Httputil code reference from "the first line of Android" 10th Chapter 5, just replaced HttpURLConnection HttpClient. Parsejsonwithjsonobject reference from 400 pages of the book. The book author Guo Lin, csdn Blog: http://blog.csdn.net/guolin_blog/.

2, the code reference from http://programmerguru.com/android-tutorial/ Android-restful-webservice-tutorial-how-to-call-restful-webservice-in-android-part-3/?utm_source=tuicool. This article contains a total of three parts, showing the application of Restful Webservice in Android development by demonstrating an example of a front-end backend. There was no problem with Android at the time of debugging, but the server side created the Dynamic web with Eclipse EE, ran the Times wrong, debugging found that Class.forName (constants.dbclass) error, String Dbclass = "Com.mysql.jdbc.Driver", download a com.mysql.jdbc.Driver import to succeed.

3, the code reference from the "first line of Android" author Guo Lin's blog: http://blog.csdn.net/guolin_blog/article/details/17482095. Testing the code encountered several problems: first of all, because of the firewall, volley can not use Git directly clone, have to set up the agent to successfully download. The second problem is volley jar package generation, there are many methods on the net, but I didn't succeed in it. For example, Stormzhang's command line, the Guo Lin export jar package through eclipse, could be due to a version update, none of these methods, and later build the jar package successfully with Android Studio. Finally, it can be used smoothly in the project. The third problem is my own low-level error, the Web server directly using the above Asynchttpclient service-side program, the Android side Post data past, but I did not notice that the servers can only handle get URLs, because the previous use of thinkphp is not differentiated Get and post are handled the same way. Did not expect the Java side to distinguish, took a lot of time to find out.

Android Development-Network communication 2

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.