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/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.jsontest.MainActivity"
    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" />
        
        <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:gravity="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>
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.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 MainActivity extends 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() {
			
			@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的索引,根据索引获取值
										userPsw = jsonData.getString("userPsw"); //userPsw是来源于服务器端php程序响应结果res的索引,根据索引获取值
										data.add("用户ID:" + userId + ",用户密码:" + userPsw); //保存返回的值,可进行相应的操作,这里只进行显示
									}
									
									Looper.prepare();
									Toast.makeText(MainActivity.this, data.toString(), Toast.LENGTH_LONG).show();
									Looper.loop();
								}
								else {
									Looper.prepare();
									Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_LONG).show();
									Looper.loop();
								}
							}
							catch(Exception 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 activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

而下面是一个服务器端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);
?>




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值