Android+PHP 使用HttpClient提交POST的请求,使用JSON解析响应
这里介绍一下如何让自己的Android程序具有联网功能。当然首先要有一台服务器,如果只是进行测试的话,可以使用局域网代替(手机连电脑wifi)。
要求电脑已配置好Apache+PHP环境。
下面是一个简单的Android程序,相信只要有一定的Java基础就能大概“猜懂”其中的含义。(程序可能写的不够完善)
Android程序
布局文件
<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:>gravity="center" android:text="使用JSON解析" android:textSize="30sp"/> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:>gravity="center"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="账号" android:textsize="20sp" android:layout_marginright="20dp"></textview> <edittext android:id="@+id/et_id" android:layout_width="match_parent" android:layout_height="wrap_content"></edittext> </linearlayout> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:>gravity="center"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密码" android:textsize="20sp" android:layout_marginright="20dp"></textview> <edittext android:id="@+id/et_psw" android:layout_width="match_parent" android:layout_height="wrap_content"></edittext> </linearlayout> <button android:id="@+id/btn_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="登录"></button> </textview></linearlayout>
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 索引,根据<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); } } </string></string></namevaluepair></namevaluepair>
而下面是一个服务器端php文件(文件内并未连接数据库的操作,如果希望的话,可以连接数据库,获取动态数据。对于php有所了解的人可以很容易的改成连接数据库获取数据的操作)
checkId.php
<?php //获取客户端发送过来的ID和密码 $id=$_POST['id']; $psw=$_POST['psw']; if($id == "admin" && $psw == "123") { $res=array(array()); $res[0]['userId']=$id; $res[0]['userPsw']=$psw; $res[1]['userId']="testId1"; $res[1]['userPsw']="testPsw1"; $res[2]['userId']="testId2"; $res[2]['userPsw']="testPsw2"; } echo json_encode($res); ?>
以上就介绍了Android+PHP 使用HttpClient提交POST的请求,使用JSON解析响应,包括了gravity,Apache,Exception,索引,连接数据库方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

最近几天,Ice Universe 不断披露有关 Galaxy S25 Ultra 的详细信息,人们普遍认为这款手机将是三星的下一款旗舰智能手机。除此之外,泄密者声称三星只计划升级一款相机

OnLeaks 现在与 Android Headlines 合作,首次展示了 Galaxy S25 Ultra,几天前,他试图从他的 X(以前的 Twitter)粉丝那里筹集到 4,000 美元以上的资金,但失败了。对于上下文,嵌入在 h 下面的渲染图像

除了发布两款新智能手机外,TCL 还发布了一款名为 NXTPAPER 14 的新 Android 平板电脑,其大屏幕尺寸是其卖点之一。 NXTPAPER 14 采用 TCL 标志性品牌哑光液晶面板 3.0 版本

Vivo Y300 Pro刚刚全面亮相,它是最薄的中端Android手机之一,配备大电池。准确来说,这款智能手机的厚度仅为 7.69 毫米,但配备了 6,500 mAh 的电池。这与最近推出的容量相同

三星尚未就何时更新其 Fan Edition (FE) 智能手机系列提供任何提示。目前来看,Galaxy S23 FE 仍然是该公司的最新版本,于 2023 年 10 月年初推出。

最近几天,Ice Universe 不断披露有关 Galaxy S25 Ultra 的详细信息,人们普遍认为这款手机将是三星的下一款旗舰智能手机。除此之外,泄密者声称三星只计划升级一款相机

Redmi Note 14 Pro Plus 现已正式成为去年 Redmi Note 13 Pro Plus 的直接后继产品(亚马逊售价 375 美元)。正如预期的那样,Redmi Note 14 Pro Plus与Redmi Note 14和Redmi Note 14 Pro一起成为Redmi Note 14系列的主角。李

OnePlus的姐妹品牌iQOO的2023-4年产品周期可能即将结束;尽管如此,该品牌已宣布 Z9 系列的开发尚未结束。它的最终版,也可能是最高端的 Turbo+ 变体刚刚按照预测发布。时间
