實現安卓客戶端發送json數據到jsp服務器解析,然後對數據進行相應地處理後,再以json的形式返回客戶端,客戶端接收判斷並處理。
以下是安卓客戶端的關鍵代碼:
username = name.getText().toString();
password = pass.getText().toString();
HttpPost request = new HttpPost(URL);
JSONObject p=new JSONObject();
try {
p.put("username", username);
p.put("password", password);
StringEntity s;
try {
s = new StringEntity(p.toString());
System.out.println(p.toString());
request.setEntity(s);
HttpResponse res=new DefaultHttpClient().execute(request);
String ret=EntityUtils.toString(res.getEntity());
JSONObject result=new JSONObject(ret);
String take=result.getString("index");
System.out.println("index......"+take);
if(take.trim().equals("yes"))
{
Toast.makeText(MainActivity.this, "登陸成功", 2).show();
}else if(take.trim().equals("no"))
{
Toast.makeText(MainActivity.this, "密碼錯誤或沒有該用戶", 2).show();
}else
{
Toast.makeText(MainActivity.this, "服務器錯誤", 2).show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsp服務器端的關鍵源碼:
<%@page import="net.sf.json.util.JSONStringer"%>
<%@page import="java.io.InputStream"%>
<%@page import="net.sf.json.JSONString"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="java.io.OutputStream"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.test1.*" %>
<%
System.out.println("username======="+request.getParameter("username"));
String name=request.getParameter("username");
String pass=request.getParameter("password");
Login1 log=new Login1();
InputStream jsonStream=request.getInputStream();
String mess=log.inputStream2String(jsonStream);
System.out.println("mess>>>"+mess);
String index=log.login(log.parseJson(mess).getId(), log.parseJson(mess).getPassword());
String index=log.login(name, pass);
System.out.println("INDEX>>>"+index);
JSONObject js=new JSONObject();
js.put("index", index);
System.out.println(js.toString());
out.println(js);
System.out.println(index);
%>