使用json数据交互信息
首先搭配SSH服务端,目前只用了Struts2,首先导入包,下面是需要的包
web.xml的代码
- <?xmlversion="1.0"encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
struts.xml代码
- <?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
- <struts>
- <packagename="as"extends="json-default">
- <actionname="login"class="as.action.LoginAction"method="login">
- <resulttype="json"></result>
- </action>
- </package>
- </struts>
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
- <struts>
- <package name="as" extends="json-default">
- <action name="login" class="as.action.LoginAction" method="login">
- <result type="json" ></result>
- </action>
- </package>
- </struts>
项目的结构
LoginAction.java代码
- package as.action;
- import java.util.HashMap;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.interceptor.ServletRequestAware;
- import org.apache.struts2.interceptor.ServletResponseAware;
- import net.sf.json.JSONObject;
- import as.model.User;
- import com.opensymphony.xwork2.ActionSupport;
- import com.opensymphony.xwork2.ModelDriven;
- public class LoginActionextends ActionSupport implements ServletResponseAware ,ServletRequestAware,ModelDriven<User>{
- private User user;
- private HttpServletResponse response;
- private HttpServletRequest request;
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- public void setServletResponse(HttpServletResponse arg0) {
- // TODO Auto-generated method stub
- this.response = arg0;
- }
- public void setServletRequest(HttpServletRequest arg0) {
- // TODO Auto-generated method stub
- this.request=arg0;
- }
- public void login() {
- try {
- // TODO Auto-generated method stub
- this.response.setContentType("text/html;charset=utf-8");
- this.response.setCharacterEncoding("UTF-8");
- JSONObject json=new JSONObject();
- Map map=new HashMap<Object, String>();
- map.put("name", user.getName());
- map.put("pwd", user.getPwd());
- json.put("LoginInfo", map);
- response.getWriter().write(json.toString());
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- public User getModel() {
- // TODO Auto-generated method stub
- if (user==null) {
- return user=new User();
- }
- return user;
- }
- }
- package as.action;
- import java.util.HashMap;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.interceptor.ServletRequestAware;
- import org.apache.struts2.interceptor.ServletResponseAware;
- import net.sf.json.JSONObject;
- import as.model.User;
- import com.opensymphony.xwork2.ActionSupport;
- import com.opensymphony.xwork2.ModelDriven;
- public class LoginAction extends ActionSupport implements ServletResponseAware ,ServletRequestAware,ModelDriven<User>{
- private User user;
- private HttpServletResponse response;
- private HttpServletRequest request;
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- public void setServletResponse(HttpServletResponse arg0) {
- // TODO Auto-generated method stub
- this.response = arg0;
- }
- public void setServletRequest(HttpServletRequest arg0) {
- // TODO Auto-generated method stub
- this.request=arg0;
- }
- public void login() {
- try {
- // TODO Auto-generated method stub
- this.response.setContentType("text/html;charset=utf-8");
- this.response.setCharacterEncoding("UTF-8");
- JSONObject json=new JSONObject();
- Map map=new HashMap<Object, String>();
- map.put("name", user.getName());
- map.put("pwd", user.getPwd());
- json.put("LoginInfo", map);
- response.getWriter().write(json.toString());
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- public User getModel() {
- // TODO Auto-generated method stub
- if (user==null) {
- return user=new User();
- }
- return user;
- }
- }
User.java
- package as.model;
- public class User {
- private String name;
- private String pwd;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPwd() {
- return pwd;
- }
- public void setPwd(String pwd) {
- this.pwd = pwd;
- }
- }
- package as.model;
- public class User {
- private String name;
- private String pwd;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPwd() {
- return pwd;
- }
- public void setPwd(String pwd) {
- this.pwd = pwd;
- }
- }
view层 index.jsp 代码
- <%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'index.jsp' starting page</title>
- <metahttp-equiv="pragma"content="no-cache">
- <meta http-equiv="cache-control"content="no-cache">
- <metahttp-equiv="expires"content="0">
- <meta http-equiv="keywords"content="keyword1,keyword2,keyword3">
- <metahttp-equiv="description"content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <center>
- <formaction="login"method="post">
- 用户名: <inputtype="text"name="name"><br>
- 密 码: <inputtype="password"name="pwd"><br>
- <input type="submit"value="登陆"name="submit"> <input type="reset"value="取消"name="reset">
- </form>
- </center>
- </body>
- </html>
- 测试 用户名:2222 密码:1111
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <center>
- <form action="login" method="post">
- 用户名: <input type="text" name="name"><br>
- 密 码: <input type="password" name="pwd"><br>
- <input type="submit" value="登陆" name="submit"> <input type="reset" value="取消" name="reset">
- </form>
- </center>
- </body>
- </html>
- 测试 用户名:2222 密码:1111
现在在android上面测试,Android 项目构架
由于是post 请求,这里就给出Android post 请求的代码
UrlServiceImpl.java
111.122.31.54 是本机的IP地址
- package dlnu.message.serviceimpl;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- 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.params.CoreConnectionPNames;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- import dlnu.message.service.UrlService;
- public class UrlServiceImplimplements UrlService{
- @Override
- public String Login(String name, String pwd) {
- // TODO Auto-generated method stub
- String uriAPI = "http://111.122.31.54:8080/AndroidService/login.action";
- /*建立HTTPost对象*/
- HttpPost httpRequest = new HttpPost(uriAPI);
- HttpClient client=new DefaultHttpClient();
- /*
- * NameValuePair实现请求参数的封装
- */
- //System.out.println("--------"+name+"-----------"+pwd);
- List <NameValuePair> params = new ArrayList <NameValuePair>(2);
- params.add(new BasicNameValuePair("name", name));//返回JSon数据 如果是xml 返回的就是XML数据
- params.add(new BasicNameValuePair("pwd", pwd));
- String strResult=null;
- try
- {
- /* 添加请求参数到请求对象*/
- httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
- /* 处理超时*/
- client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
- /*发送请求并等待响应*/
- HttpResponse httpResponse = client.execute(httpRequest);
- /*若状态码为200 ok*/
- if(httpResponse.getStatusLine().getStatusCode() ==200)
- {
- /*读返回数据 去掉两头不要的参数*/
- strResult= EntityUtils.toString(httpResponse.getEntity());
- }
- else
- {
- System.err.println("Error Response: "+httpResponse.getStatusLine().toString());
- strResult=null;
- }
- }
- catch (ClientProtocolException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- return strResult;
- }
- }
- package dlnu.message.serviceimpl;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- 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.params.CoreConnectionPNames;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- import dlnu.message.service.UrlService;
- public class UrlServiceImpl implements UrlService{
- @Override
- public String Login(String name, String pwd) {
- // TODO Auto-generated method stub
- String uriAPI = "http://111.122.31.54:8080/AndroidService/login.action";
- /*建立HTTPost对象*/
- HttpPost httpRequest = new HttpPost(uriAPI);
- HttpClient client=new DefaultHttpClient();
- /*
- * NameValuePair实现请求参数的封装
- */
- //System.out.println("--------"+name+"-----------"+pwd);
- List <NameValuePair> params = new ArrayList <NameValuePair>(2);
- params.add(new BasicNameValuePair("name", name));//返回JSon数据 如果是xml 返回的就是XML数据
- params.add(new BasicNameValuePair("pwd", pwd));
- String strResult=null;
- try
- {
- /* 添加请求参数到请求对象*/
- httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
- /* 处理超时*/
- client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
- /*发送请求并等待响应*/
- HttpResponse httpResponse = client.execute(httpRequest);
- /*若状态码为200 ok*/
- if(httpResponse.getStatusLine().getStatusCode() == 200)
- {
- /*读返回数据 去掉两头不要的参数*/
- strResult= EntityUtils.toString(httpResponse.getEntity());
- }
- else
- {
- System.err.println("Error Response: "+httpResponse.getStatusLine().toString());
- strResult=null;
- }
- }
- catch (ClientProtocolException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- return strResult;
- }
- }
Activity ShowMessageMainActivity.java
- package dlnu.message.activity;
- import dlnu.message.model.User;
- import dlnu.message.service.UserService;
- import dlnu.message.serviceimpl.JsonServiceImpl;
- import dlnu.message.serviceimpl.UserServiceImpl;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- public class ShowMessageMainActivityextends Activity {
- /** Called when the activity is first created. */
- private EditText namEditText;
- private EditText pwdEditText;
- private Button submitButton;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.showmessageactivity);
- namEditText=(EditText) findViewById(R.id.nameditText1);
- pwdEditText=(EditText) findViewById(R.id.pwdseditText2);
- submitButton=(Button) findViewById(R.id.submitbutton1);
- submitButton.setOnClickListener(new ButtonListener());
- }
- class ButtonListenerimplements OnClickListener{
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- String name=namEditText.getText().toString().trim();
- String pwd=pwdEditText.getText().toString().trim();
- UserService userService=new UserServiceImpl();
- JsonServiceImpl service=new JsonServiceImpl();
- String string=userService.UserLogin(name, pwd);
- User user=new User();
- user=service.UserLoginJsonAnalysis(string);
- Toast.makeText(ShowMessageMainActivity.this, user.getName()+" "+user.getPwd(),8000).show();
- }
- }
- }
- package dlnu.message.activity;
- import dlnu.message.model.User;
- import dlnu.message.service.UserService;
- import dlnu.message.serviceimpl.JsonServiceImpl;
- import dlnu.message.serviceimpl.UserServiceImpl;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- public class ShowMessageMainActivity extends Activity {
- /** Called when the activity is first created. */
- private EditText namEditText;
- private EditText pwdEditText;
- private Button submitButton;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.showmessageactivity);
- namEditText=(EditText) findViewById(R.id.nameditText1);
- pwdEditText=(EditText) findViewById(R.id.pwdseditText2);
- submitButton=(Button) findViewById(R.id.submitbutton1);
- submitButton.setOnClickListener(new ButtonListener());
- }
- class ButtonListener implements OnClickListener{
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- String name=namEditText.getText().toString().trim();
- String pwd=pwdEditText.getText().toString().trim();
- UserService userService=new UserServiceImpl();
- JsonServiceImpl service=new JsonServiceImpl();
- String string=userService.UserLogin(name, pwd);
- User user=new User();
- user=service.UserLoginJsonAnalysis(string);
- Toast.makeText(ShowMessageMainActivity.this, user.getName()+" "+user.getPwd(), 8000).show();
- }
- }
- }
效果