Android+php using HttpClient to submit a POST request, use JSON to parse the response

Source: Internet
Author: User
here's how to get your Android app to have networking capabilities. Of course, the first to have a server, if only for testing, you can use the local area network instead (mobile phone and computer WiFi).

Requires that the computer is configured with Apache+php environment.

Here is a simple Android program, I believe that as long as there is a certain Java foundation can probably "guess" the meaning of it. (The program may not be well written)

Android Program

Layout file

     
  
   Gravity= "Center" android:text= "parse with JSON" android:textsize= "30SP"/>
   
     
    gravity= "center" > 
      
                      
     

       
   
    
    gravity= "center" > 
      
                     
     

           
   
  
 
Main Activity. Java

Package Com.example.jsontest;import Java.io.bufferedreader;import Java.io.inputstream;import Java.io.inputstreamreader;import java.util.arraylist;import java.util.list;import org.Apache. http. httpentity;import org.Apache. http. httpresponse;import org.Apache. http. namevaluepair;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 org.Apache. Http.protocol.http;import Org.json.jsonarray;import Org.json.jsonobject;import Android.os.Bundle;import Android.os.looper;import Android.support.v7.app.ActionBarActivity; Import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.toast;public class MainActivityExtends ActionBarActivity{EditText et_id; EditText ET_PSW;    Button Btn_login;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.Activity_main);    Initview (); The private Boolean check (string ID, string psw) {if ("". Equals (ID) | | "".    Equals (PSW)) return false;    return true;    } private void Initview () {et_id = (EditText) Findviewbyid (r.id.et_id);    ET_PSW = (EditText) Findviewbyid (R.ID.ET_PSW);        Btn_login = (Button) Findviewbyid (R.id.btn_login); Btn_login.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method stub//gets the user name and password of the user input final string id = Et_id.gettext (). ToString (). Trim (); final string psw = Et_psw.gettext (). ToString (). Trim (), if (check (ID, PSW)) {new Thread () {public void run () {try {HttpPost post = new HttpPost ("Change this to the server file's URL address");//If the pass parameter More than one number, you can encapsulate the passed parameters list
 
  params = new ArrayList
  
   
();p Arams.add (new Basicnamevaluepair ("id", id));p arams.add (New Basicnamevaluepair ("PSW", PSW);// Set the request parameter Post.setentity (new urlencodedformentity (params, HTTP. Utf_8)); HttpClient HttpClient = new Defaulthttpclient ();//Send POST request HttpResponse response = Httpclient.execute (post);// If the server succeeds in returning the response if (Response.getstatusline (). Getstatuscode () = = () {//string msg = entityutils.tostring ( Response.getentity ()); httpentity entity = response.getentity (); InputStream is = Entity.getcontent (); BufferedReader reader = new BufferedReader (new InputStreamReader (IS, "Utf-8"), 8); StringBuilder sb = new StringBuilder (); Sb.append (Reader.readline () + "\ n"); Here "+" \ n "" Plus does not seem to have any effect on the results of string line = "0", while ((line = Reader.readline ()) = null) {Sb.append (line + "\ n"); Here "+" \ n "" added does not seem to have any effect on the result}is.close ();//Gets the request response result string = Sb.tostring (); SYSTEM.OUT.PRINTLN (result);//packaged into JSON for parsing jsonarray jsonarray = new Jsonarray (result); Jsonobject Jsondata = null;//Returns the user ID, user password, string userId = ""; String USERPSW = "";//Use LisT to store the list 
   
    data = new ArrayList
    
     (); for (int i = 0; i < jsonarray.length (); i++) {jsondata = Jsonarray.getjsonobject (i); userId = jsondata.getstring ("User Id "); The userid is derived from the server-side PHP program Response result Res
     IndexUnder
     IndexGets the value USERPSW = jsondata.getstring ("USERPSW"); USERPSW is derived from the server-side PHP program Response result Res
     IndexUnder
     IndexGet the value Data.add ("User id:" + userId + ", User password:" + USERPSW); Save the returned value, you can do the corresponding operation, here only display}looper.prepare (); Toast.maketext (Main
     Activity. This, data.tostring (), Toast.length_long). Show (); Looper.loop ();} else {looper.prepare (); Toast.maketext (Main
     Activity. This, "Login failed", Toast.length_long). Show (); Looper.loop ();}} Catch
     Exceptione) {e.printstacktrace ();}}}.    Start ();}}); } @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; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent
     ActivityInch
     Androidmanifest.xml.        int id = item.getitemid ();        if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }}
    
   
  
 

The following is a server-side PHP file (the file is not connected to the database operation, if you want, you can connect to the database , to obtain Dynamic data.) People who know PHP can easily change to connect to the database to get the data of the operation.

checkid.php

 
  


The above describes the android+php using HttpClient to submit a POST request, the use of JSON parsing response, including gravity,apache,exception, index, connection database content, I hope to be interested in PHP tutorial friends helpful.

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