• J2EE 练习题


    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

      <project 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">
          <modelVersion>4.0.0</modelVersion>
          <groupId>lld</groupId>
          <artifactId>http.json.test.server</artifactId>
          <packaging>war</packaging>
          <version>0.0.1-SNAPSHOT</version>
          <name>http.json.test.server Maven Webapp</name>
          <url>http://maven.apache.org</url>
          <properties>
              <gson.version>2.8.2</gson.version>
              <tomcat.version>6.0.53</tomcat.version>
          </properties>
          <dependencies>
              <dependency>
                  <groupId>com.google.code.gson</groupId>
                  <artifactId>gson</artifactId>
                  <version>${gson.version}</version>
              </dependency>
              <dependency>
                  <groupId>org.apache.tomcat</groupId>
                  <artifactId>servlet-api</artifactId>
                  <version>${tomcat.version}</version>
                  <scope>provided</scope>
              </dependency>
              <dependency>
                  <groupId>junit</groupId>
                  <artifactId>junit</artifactId>
                  <version>3.8.1</version>
                  <scope>test</scope>
              </dependency>
          </dependencies>
          <build>
              <finalName>http.json.test.server</finalName>
          </build>
      </project>
    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

      <!DOCTYPE web-app PUBLIC
       "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
       "http://java.sun.com/dtd/web-app_2_3.dtd" >
      
      <web-app>
          <display-name>HTTP JSON Service Demo</display-name>
          <servlet>
              <servlet-name>getUser</servlet-name>
              <servlet-class>http.json.test.server.servlet.UserServlet</servlet-class>
          </servlet>
      
          <servlet-mapping>
              <servlet-name>getUser</servlet-name>
              <url-pattern>/getUser.do</url-pattern>
          </servlet-mapping>
      </web-app>
      
    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

      <project 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">
          <modelVersion>4.0.0</modelVersion>
      
          <groupId>lld</groupId>
          <artifactId>http.json.test.client</artifactId>
          <version>0.0.1-SNAPSHOT</version>
          <packaging>jar</packaging>
      
          <name>http.json.test.client</name>
          <url>http://maven.apache.org</url>
      
          <properties>
              <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
          </properties>
      
          <dependencies>
              <dependency>
                  <groupId>org.apache.httpcomponents</groupId>
                  <artifactId>httpclient</artifactId>
                  <version>4.5.2</version>
              </dependency>
          </dependencies>
      </project>
    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<String, String> parameters) throws ClientProtocolException, IOException {
              return callHttpService(url, parameters, "utf-8");
          }
          
          public static String callHttpService(String url, Map<String, String> parameters, String charset) throws ClientProtocolException, IOException {
              String result = null;
              HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
              CloseableHttpClient httpClient = httpClientBuilder.build();
              HttpPost httpPost = new HttpPost(url);
      
              List<NameValuePair> list = new ArrayList<NameValuePair>();
      
              if (parameters != null) {
                  Iterator<Map.Entry<String, String>> iterator = parameters.entrySet().iterator();
      
                  while (iterator.hasNext()) {
                      Entry<String, String> entry = (Entry<String, 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<string, string=""> parameters = new HashMap<string, string="">();
              parameters.put("userId", "lld");
              String result = HttpRequestUtil.callHttpService(url, parameters);
              System.out.println("Result is: ");
              System.out.println(result);        
          }
      }
  • 相关阅读:
    GitBook基本使用
    Window 远程桌面漏洞风险,各个厂家的扫描修复方案(CVE-2019-0708)
    应急响应实战笔记(续)
    不同系统下,复制文件时新文件的日期区别
    Window应急响应(六):NesMiner挖矿病毒
    利用python输出000至999中间的数
    揭秘骗局:这是一张会变的图片
    如何查看github排行热度
    zabbix使用自动发现功能批量监控服务器端口的可用性
    使用python脚本批量设置nginx站点的rewrite规则
  • 原文地址:https://www.cnblogs.com/lldwolf/p/7833957.html
Copyright © 2020-2023  润新知