J2EE 练习题 - JSON HTTP Service
1 要求
2 示例代码
2.1 Server 端
2.2 客户端 - Java
1 要求
在 Tomcat 上布署一个 HTTP Service,使用 JSON 格式返回数据
2 示例代码
2.1 Server 端
基于 Maven 开发
-
新建 Maven webapp 项目
-
修改 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>
-
创建 POJO 类 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; } }
-
创建 Servlet 类 UserServlet
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); } }
-
修改 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>
-
编译并打包
mvn clean package
-
将生成的 war 包复制到 Tomcat webapps 目录并启动 Tomcat,打开浏览器输入 http://localhost:8080/http.json.test.server/getUser.do?userId=10001 后在浏览器中显示结果:
{"userId":"10001","userName":"Lindong"}
2.2 客户端 - Java
使用 Java 程序获取 Service 响应
-
使用 Maven 创建 quickstart 程序
-
修改 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>
-
创建工具类 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 !=