J2EE 练习题 - JSON HTTP Service


J2EE 练习题 - JSON HTTP Service


1 要求

2 示例代码

        2.1 Server 端

        2.2 客户端 - Java


1 要求

在 Tomcat 上布署一个 HTTP Service,使用 JSON 格式返回数据

2 示例代码

2.1 Server 端

基于 Maven 开发

  1. 新建 Maven webapp 项目

  2. 修改 pom.xml 如下

    pom.xml

    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        4.0.0
        lld
        http.json.test.server
        war
        0.0.1-SNAPSHOT
        http.json.test.server Maven Webapp
        http://maven.apache.org
        
            2.8.2
            6.0.53
        
        
            
                com.google.code.gson
                gson
                ${gson.version}
            
            
                org.apache.tomcat
                servlet-api
                ${tomcat.version}
                provided
            
            
                junit
                junit
                3.8.1
                test
            
        
        
            http.json.test.server
        
    
  3. 创建 POJO 类 User.java

    User.java

    package http.json.test.server.model;
    
    public class User {
        private String userId;
        private String userName;
    
        public String getUserId() {
            return userId;
        }
    
        public void setUserId(String userId) {
            this.userId = userId;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    }
    
  4. 创建 Servlet 类 UserServlet

    UserServlet.java

    package http.json.test.server.servlet;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.google.gson.Gson;
    
    import http.json.test.server.model.User;
    
    public class UserServlet extends HttpServlet {
    
        private static final long serialVersionUID = -2118394734647389638L;
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doPost(req, resp);
        }
        
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            User user = new User();
            String userId = req.getParameter("userId");
            user.setUserId(userId);
            user.setUserName("Lindong");
            String jsonString = new Gson().toJson(user);
            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.print(jsonString);
        }
    }
    
  5. 修改 web.xml 如下所示

    web.xml

    web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    
        HTTP JSON Service Demo
        
            getUser
            http.json.test.server.servlet.UserServlet
        
    
        
            getUser
            /getUser.do
        
    
    
  6. 编译并打包

    mvn clean package
  7. 将生成的 war 包复制到 Tomcat webapps 目录并启动 Tomcat,打开浏览器输入 http://localhost:8080/http.json.test.server/getUser.do?userId=10001 后在浏览器中显示结果:

    {"userId":"10001","userName":"Lindong"}

2.2 客户端 - Java

使用 Java 程序获取 Service 响应

  1. 使用 Maven 创建 quickstart 程序

  2. 修改 pom.xml 如下

    pom.xml

    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        4.0.0
    
        lld
        http.json.test.client
        0.0.1-SNAPSHOT
        jar
    
        http.json.test.client
        http://maven.apache.org
    
        
            UTF-8
        
    
        
            
                org.apache.httpcomponents
                httpclient
                4.5.2
            
        
    
  3. 创建工具类 HttpRequestUtil.java

    HttpRequestUtil.java

    package lld.http.json.test.client.util;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    public class HttpRequestUtil {
        public static String callHttpService(String url, Map parameters) throws ClientProtocolException, IOException {
            return callHttpService(url, parameters, "utf-8");
        }
        
        public static String callHttpService(String url, Map parameters, String charset) throws ClientProtocolException, IOException {
            String result = null;
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            CloseableHttpClient httpClient = httpClientBuilder.build();
            HttpPost httpPost = new HttpPost(url);
    
            List list = new ArrayList>();
    
            if (parameters != null) {
                Iterator> iterator = parameters.entrySet().iterator();
    
                while (iterator.hasNext()) {
                    Entry entry = (Entry, String>) iterator.next();
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
    
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }
            
            HttpResponse response = httpClient.execute(httpPost);
    
            if (response != null) {
                HttpEntity responseEntity = response.getEntity();
                
                if (responseEntity != null) {
                    result = EntityUtils.toString(responseEntity);
                }
            }
            
            return result;
        }
    }
  4. 调用 Http Service 例程

    App.java

    package lld.http.json.test.client;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.apache.http.client.ClientProtocolException;
    
    import lld.http.json.test.client.util.HttpRequestUtil;
    
    /**
     * Hello world!
     *
     */
    public class App 
    {
        public static void main( String[] args ) throws ClientProtocolException, IOException
        {
            String url = "http://localhost:8080/http.json.test.server/getUser.do";
            Map parameters = new HashMap();
            parameters.put("userId", "lld");
            String result = HttpRequestUtil.callHttpService(url, parameters);
            System.out.println("Result is: ");
            System.out.println(result);        
        }
    }