android 与servlet json数据交互

本文介绍了一个简单的Android应用如何通过HTTP Post方式与服务器进行JSON数据交互。应用使用Apache HttpClient发送带有JSON数据的请求,并从服务器接收JSON响应。服务器端通过Servlet处理请求并返回相应的JSON数据。
摘要由CSDN通过智能技术生成

android客户



package com.comingx.xzz;
 
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class Main extends Activity {
 
	private static final String TAG = "Main";
	private EditText nameEdit;
	private EditText phoneEdit;
	private EditText resultEdit;
	private Button sendBtn;
	private ProgressDialog progressDialog;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		nameEdit = (EditText) findViewById(R.id.name);
		phoneEdit = (EditText) findViewById(R.id.phone);
		resultEdit = (EditText) findViewById(R.id.result);
		sendBtn = (Button) findViewById(R.id.sendBtn);
		progressDialog = new ProgressDialog(this);
 
		sendBtn.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				new AT().execute(nameEdit.getText().toString() , phoneEdit.getText().toString());
			}
		});
	}
	class AT extends AsyncTask{
 
		@Override
		protected void onPreExecute() {
			progressDialog.show();
		}
 
		@Override
		protected String doInBackground(String... params) {
			try {
				//请求数据
				HttpClient hc = new DefaultHttpClient();
				HttpPost hp = new HttpPost(
						"http://192.168.1.102:8080/JSONServlet/JSONServlet");
				//请求json报文
				JSONObject jo = new JSONObject();
				if (params.length > 1) {
					jo.put("name", params[0]);
					jo.put("phone", params[1]);
				} else {
					jo.put("err", "error");
				}
				Log.d(TAG, "params : " + jo.toString());
				hp.setEntity(new StringEntity(jo.toString()));
				HttpResponse hr = hc.execute(hp);
				String result = null;
				//获取返回json报文
				if(hr.getStatusLine().getStatusCode() == 200){
					result = EntityUtils.toString(hr.getEntity());
					Log.d(TAG, "result : " + result);
				}
				//关闭连接
				if (hc != null) {
					hc.getConnectionManager().shutdown();
				}
				return result;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
 
		@Override
		protected void onPostExecute(String result) {
			resultEdit.setText(result);
			progressDialog.cancel();
		}
	}
}



服务器代码:
package com.comingx.xzz;
 
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Enumeration;
 
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class JSONServlet
 */
public class JSONServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String result = "";
		try {
			/* 读取数据 */
			BufferedReader br = new BufferedReader(
					new InputStreamReader((ServletInputStream) req.getInputStream(), "utf-8"));
			StringBuffer sb =new StringBuffer("");
			String temp;
			while((temp=br.readLine())!=null){
				sb.append(temp);
			}
			br.close();
			result = sb.toString();
			System.out.println("请求报文:" + result);
		} catch (Exception e) {
			result = "{err:\"error\"}";
		} finally {
			/* 返回数据 */
			System.out.println("返回报文:" + result);
			PrintWriter pw = resp.getWriter();
			pw.write(result);
			pw.flush();
			pw.close();
		}
	}
 
}



服务器就只有一个servlet来处理.

代码很明显.

android利用的是apache的httpClient来实现网络连接,将json数据储存与StringEntity中,在设置httpPost的实体setEntity()。利用HttpClient实现网络请求,再获取数据result = EntityUtils.toStirng(hr.getEntity());最后将结果显示于Edittext上。

服务器代码也很简单。

利用BufferReader封转request获取的InputStream来读取请求实体,获取请求json报文,在将报文结果输出流中,返回给客户端。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值