Home Backend Development PHP Tutorial Android+PHP uses HttpClient to submit POST requests and uses JSON to parse the response.

Android+PHP uses HttpClient to submit POST requests and uses JSON to parse the response.

Jul 29, 2016 am 09:12 AM
android import quot string

 Here’s an introduction to how to make your Android program have networking capabilities. Of course, you must first have a server. If you are just testing, you can use a LAN instead (mobile phone connected to computer wifi).

Requires the computer to be configured with Apache+PHP environment.

The following is a simple Android program. I believe that as long as you have a certain Java foundation, you can roughly "guess" its meaning. (The program may not be well written enough)

Android program

layout file

<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:paddingBottom="@dimen/<strong>Activity</strong>_vertical_margin"
    android:paddingLeft="@dimen/<strong>Activity</strong>_horizontal_margin"
    android:paddingRight="@dimen/<strong>Activity</strong>_horizontal_margin"
    android:paddingTop="@dimen/<strong>Activity</strong>_vertical_margin"
    tools:c
    android:orientation="vertical" >

    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:<strong>gravity</strong>="center"
        android:text="使用JSON解析"
        android:textSize="30sp"/>
    
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:<strong>gravity</strong>="center">
        
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="账号"
        android:textSize="20sp"
        android:layout_marginRight="20dp" />
        
        <EditText 
            android:id="@+id/et_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
    
	<LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:<strong>gravity</strong>="center">
        
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="密码"
        android:textSize="20sp"
        android:layout_marginRight="20dp" />
        
        <EditText 
            android:id="@+id/et_psw"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>    
    
	<Button 
	    android:id="@+id/btn_login"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:text="登录"/>
</LinearLayout>
Copy after login
MainActivity.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.<strong>Apache</strong>.http.HttpEntity;
import org.<strong>Apache</strong>.http.HttpResponse;
import org.<strong>Apache</strong>.http.NameValuePair;
import org.<strong>Apache</strong>.http.client.HttpClient;
import org.<strong>Apache</strong>.http.client.entity.UrlEncodedFormEntity;
import org.<strong>Apache</strong>.http.client.methods.HttpPost;
import org.<strong>Apache</strong>.http.impl.client.DefaultHttpClient;
import org.<strong>Apache</strong>.http.message.BasicNameValuePair;
import org.<strong>Apache</strong>.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.ActionBar<strong>Activity</strong>;
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 Main<strong>Activity</strong> extends ActionBar<strong>Activity</strong> {
	EditText et_id;
	EditText et_psw;
	Button btn_login;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.<strong>Activity</strong>_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() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//获取用户输入的用户名和密码
				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("这里要改成服务器文件所在URL地址");
								//如果传递参数个数比较多,可以对传递的参数进行封装
								List<NameValuePair> params = new ArrayList<NameValuePair>();
								params.add(new BasicNameValuePair("id", id));
								params.add(new BasicNameValuePair("psw", psw));
								//设置请求参数
								post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								
								HttpClient httpClient = new DefaultHttpClient();
								//发送POST请求
								HttpResponse response = httpClient.execute(post);
								//如果服务器成功地返回响应
								if(response.getStatusLine().getStatusCode() == 200) {
									//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"); // 这里 “ + "\n" ”加不加似乎对结果没有什么影响
									
									String line = "0";
									while((line = reader.readLine()) != null) {
										sb.append(line + "\n"); // 这里 “ + "\n" ”加不加似乎对结果没有什么影响
									}
									is.close();
									
									//获取请求响应结果
									String result = sb.toString();
									System.out.println(result);
									
									//打包成JSON进行解析
									JSONArray jsonArray = new JSONArray(result);
									JSONObject jsonData = null;
									//返回用户ID,用户密码
									String userId = "";
									String userPsw = "";
									//使用List进行存储
									List<String> data = new ArrayList<String>();
									for(int i = 0; i < jsonArray.length(); i++) {
										jsonData = jsonArray.getJSONObject(i);
										userId = jsonData.getString("userId"); //userId是来源于服务器端php程序响应结果res的<strong>索引</strong>,根据<strong>索引</strong>获取值
										userPsw = jsonData.getString("userPsw"); //userPsw是来源于服务器端php程序响应结果res的<strong>索引</strong>,根据<strong>索引</strong>获取值
										data.add("用户ID:" + userId + ",用户密码:" + userPsw); //保存返回的值,可进行相应的操作,这里只进行显示
									}
									
									Looper.prepare();
									Toast.makeText(Main<strong>Activity</strong>.this, data.toString(), Toast.LENGTH_LONG).show();
									Looper.loop();
								}
								else {
									Looper.prepare();
									Toast.makeText(Main<strong>Activity</strong>.this, "登录失败", Toast.LENGTH_LONG).show();
									Looper.loop();
								}
							}
							catch(<strong>Exception</strong> e) {
								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 <strong>Activity</strong> in <strong>AndroidManifest.xml</strong>.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
Copy after login

And the following is a server-side php file (within the file For operations that have not connected to the database, if you want, you can connect to the database and obtain dynamic data. People who know PHP can easily change it to connect to the databaseto obtain data)

checkId. php

<?php
	//获取客户端发送过来的ID和密码
	$id=$_POST[&#39;id&#39;];
	$psw=$_POST[&#39;psw&#39;];

	if($id == "admin" && $psw == "123") {
		$res=array(array());
		$res[0][&#39;userId&#39;]=$id;
		$res[0][&#39;userPsw&#39;]=$psw;

		$res[1][&#39;userId&#39;]="testId1";
		$res[1][&#39;userPsw&#39;]="testPsw1";

		$res[2][&#39;userId&#39;]="testId2";
		$res[2][&#39;userPsw&#39;]="testPsw2";
	}

	echo json_encode($res);
?>
Copy after login


The above introduces Android+PHP using HttpClient to submit POST requests and using JSON to parse the response, including gravity, Apache, Exception, index, and database connection. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship Sep 10, 2024 am 06:45 AM

OnePlus'sister brand iQOO has a 2023-4 product cycle that might be nearlyover; nevertheless, the brand has declared that it is not done with itsZ9series just yet. Its final, and possibly highest-end,Turbo+variant has just beenannouncedas predicted. T

See all articles