zoukankan      html  css  js  c++  java
  • android使用JSON进行网络数据交换(服务端、客户端)的实现

    服务端需要加上json.jar包,下载地址:https://github.com/upictec/org.json.me

    服务端:

    JSONDemoServlet.java

    package com.test.Demo;

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.List;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.json.me.JSONArray;
    import org.json.me.JSONObject;

    publicclass JSONDemoServlet extends HttpServlet {
    privatestaticfinallong serialVersionUID =-7368225680407826408L;
    private List<User> list;

    /**
    * 处理post方式提交的数据
    */
    @Override
    protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
    }

    /**
    * 处理get方式提交的数据
    */
    @Override
    protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/plain");
    response.setCharacterEncoding(
    "UTF-8");
    PrintWriter out
    = response.getWriter();

    //准备用户数据
    prepareData();

    //JSON数组
    JSONArray array =new JSONArray();

    for(User bean:list){
    //单个用户JSON对象
    JSONObject obj =new JSONObject();
    try{

    obj.put(
    "id", bean.getId());
    obj.put(
    "name", bean.getName());
    obj.put(
    "email", bean.getEmail());
    obj.put(
    "gender", bean.getGender());
    }
    catch (Exception e) {
    // TODO: handle exception
    }
    array.put(obj);
    }
    //输出
    out.write(array.toString());
    out.flush();
    out.close();
    }


    privatevoid prepareData()
    {
    list
    =new ArrayList<User>();
    User bean1
    =new User();
    bean1.setId(
    1001);
    bean1.setName(
    "Tony");
    bean1.setEmail(
    "tony@toeach.net");
    bean1.setGender(
    "male");
    list.add(bean1);

    User bean2
    =new User();
    bean2.setId(
    1002);
    bean2.setName(
    "Jack");
    bean2.setEmail(
    "jack@hotmail.com");
    bean2.setGender(
    "male");
    list.add(bean2);

    User bean3
    =new User();
    bean3.setId(
    1003);
    bean3.setName(
    "Marry");
    bean3.setEmail(
    "marry@163.com");
    bean3.setGender(
    "female");
    list.add(bean3);

    User bean4
    =new User();
    bean4.setId(
    1004);
    bean4.setName(
    "Linda");
    bean4.setEmail(
    "linda@21cn.com");
    bean4.setGender(
    "female");
    list.add(bean4);
    }

    }

    User.java

    package com.test.Demo;

    publicclass User {
    privateint id;

    private String name;

    private String email;

    private String gender;

    public String getEmail() {
    return email;
    }

    publicvoid setEmail(String email) {
    this.email = email;
    }

    public String getGender() {
    return gender;
    }

    publicvoid setGender(String gender) {
    this.gender = gender;
    }

    publicint getId() {
    return id;
    }

    publicvoid setId(int id) {
    this.id = id;
    }

    public String getName() {
    return name;
    }

    publicvoid setName(String name) {
    this.name = name;
    }

    }

    web.xml中配置映射路径:

    <?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">

    <servlet>
    <servlet-name>JSONDemoServlet</servlet-name>
    <servlet-class>com.test.Demo.JSONDemoServlet</servlet-class>
    </servlet>

    <servlet-mapping>
    <servlet-name>JSONDemoServlet</servlet-name>
    <url-pattern>/JSONDemoServlet</url-pattern>
    </servlet-mapping>


    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    </web-app>

    客户端:

    package com.test;

    import java.io.BufferedReader;
    import java.io.InputStreamReader;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;

    publicclass MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    publicvoid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    try {
    StringBuffer sb
    =new StringBuffer();
    // 在测试过程中,经常是用本机做测试服务器,访问本机的IP地址要设置为10.0.2.2
    String url ="http://10.0.2.2:8080/article/JSONDemoServlet";
    String body
    = getContent(url);
    JSONArray array
    =new JSONArray(body);
    for (int i =0; i < array.length(); i++) {
    JSONObject obj
    = array.getJSONObject(i);
    sb.append(
    "id:").append(obj.getInt("id")).append("\t");
    sb.append(
    "name:").append(obj.getString("name")).append("\r\n");
    sb.append(
    "gender:").append(obj.getString("gender")).append(
    "\t");
    sb.append(
    "email:").append(obj.getString("email")).append(
    "\r\n");
    sb.append(
    "----------------------\r\n");
    }
    TextView textView
    = (TextView) findViewById(R.id.textView);
    textView.setText(sb.toString());
    }
    catch (Exception e) {
    // TODO: handle exception
    }

    }

    private String getContent(String url) throws Exception {
    StringBuilder sb
    =new StringBuilder();
    HttpClient client
    =new DefaultHttpClient();
    HttpParams httpParams
    = client.getParams();

    // 设置网络超时参数
    HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
    HttpConnectionParams.setSoTimeout(httpParams,
    5000);
    HttpResponse response
    = client.execute(new HttpGet(url));
    HttpEntity entity
    = response.getEntity();
    if (entity !=null) {
    BufferedReader reader
    =new BufferedReader(new InputStreamReader(
    entity.getContent(),
    "UTF-8"), 8192);
    String line
    =null;
    while ((line = reader.readLine()) !=null) {
    sb.append(line
    +"\n");
    }
    reader.close();
    }

    return sb.toString();
    }

    }

    服务端截图:

    客户端截图:

  • 相关阅读:
    微信小程序学习随笔
    SqlServer索引假脱机的解决
    web服务器出现大量CLOSE_WAIT连接的前因后果
    SqlServer和mysql字段拼接方法
    使用beego创建员工加班调休系统
    在c#程序中初步使用redis
    使用golang实现批量发送面试邀请邮件
    记c# rabbitmq的使用
    项目中使用mongodb的尝试
    手机集成支付宝支付功能的注意事项
  • 原文地址:https://www.cnblogs.com/tanlon/p/1989454.html
Copyright © 2011-2022 走看看