Android + PHP uses HttpClient to submit a POST request and parse the response in JSON format.

Source: Internet
Author: User
: This article describes how to use HttpClient to submit POST requests in Android + PHP and parse responses in JSON format. For more information about PHP tutorials, see. This section describes how to enable the networking function of your Android program. Of course, there must be a server first. if it is just for testing, you can use a LAN instead (mobile phone connected to a computer wifi ).

The computer is required to be configuredApache+ PHP environment.

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

Android program

Layout file

     
  
   
Gravity= "Center" android: text = "JSON parsing" 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. logoff; 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 ();} 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 // obtain the user name and password entered by the user. final String id = et_id.getText (). toString (). trim (); final String psw = et_ps1_gettext (). toString (). trim (); if (check (id, psw) {new Thread () {public void run () {try {HttpPost post = new HttpPost ("change to the URL of the server file"); // if the number of parameters to be passed is large, you can encapsulate the List of parameters to be passed.
 
  
Params = new ArrayList
  
   
(); Params. add (new BasicNameValuePair ("id", id); params. add (new BasicNameValuePair ("psw", psw); // Set the request parameter post. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); HttpClient httpClient = new DefaultHttpClient (); // send the POST request HttpResponse response = httpClient.exe cute (post); // if the server returns the response if (response. getStatusLine (). getStatusCode () = 200) {// String msg = EntityUtils. toString (response. getEntity (); HttpE Ntity 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, the addition of "+" \ n "does not seem to affect the result. String line =" 0 "; while (line = reader. readLine ())! = Null) {sb. append (line + "\ n"); // The addition of "+" \ n "does not seem to affect the result} is. close (); // get the request response result String result = sb. toString (); System. out. println (result); // package into JSON for parsing JSONArray jsonArray = new JSONArray (result); JSONObject jsonData = null; // return 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 ("userId"); // userId is derived from the res response result of the php program on the server.
     Index, According
     IndexGet the value userPsw = jsonData. getString ("userPsw"); // userPsw is from the server-side php program response result res
     Index, According
     IndexObtain the value data. add ("User ID:" + userId + ", user password:" + userPsw); // Save the returned value and perform corresponding operations. only the returned value is displayed here.} logoff. prepare (); Toast. makeText (Main
     Activity. This, data. toString (), Toast. LENGTH_LONG). show (); Lorule. loop () ;}else {Lorule. prepare (); Toast. makeText (Main
     Activity. This, "logon failed", Toast. LENGTH_LONG). show (); logoff. loop () ;}} catch (
     ExceptionE) {e. printStackTrace ();}}}. start () ;}}) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action 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 will // automatically handle clicks on the Home/Up button, so long // as you specify a parent
     ActivityIn
     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 does not containConnect to databaseIf you want to, you canConnect to databaseTo obtain dynamic data. People who know something about php can easily change itConnect to databaseOperations to obtain data)

CheckId. php

 


The preceding section describes how to use HttpClient to submit a POST request in Android + PHP and parse the response in JSON format, including gravity, Apache, Exception, index, and database connection, if you are interested in PHP tutorials.

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.