MacOS, Java和IDEA

在Servlet中解析Http请求上送的Json报文

2018-12-09  本文已影响28人  SpaceCat

这篇基于前面的“发送带Json报文的Http请求”和“编写返回Json报文的Servlet”两篇,这里的发送报文的测试程序直接用原来的,接收的程序是在前面环境中新增的一个Servlet。
其实,这是很常见的需求,解析Http请求上送的Json报文,其中可能包含请求的相关信息,比如查询条件,根据这些信息可以返回用户想要的结果。

1、写在前面

由于Get请求中,参数都放在URL中传递,所以,这里既然解析的是请求中的Json报文,这里说的是请求正文中的Json报文,也就是,肯定是指的POST请求,不是Get请求。

2、代码实现

在前面第一个用IDEA搭建的Java Web工程中新建一个Servlet(可以直接把原来的JsonServlet复制一份),命名为“JsonServletParseReqJson”。同时,在web.xml文件中,添加响应的servlet配置和map配置(这里将这个Servlet映射到了/jsonreq),如下:

<servlet>
        <servlet-name>JsonServlet</servlet-name>
        <servlet-class>com.web.test.JsonServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>JsonServletParseReqJson</servlet-name>
        <servlet-class>com.web.test.JsonServletParseReqJson</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>JsonServlet</servlet-name>
        <url-pattern>/json</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>JsonServletParseReqJson</servlet-name>
        <url-pattern>/jsonreq</url-pattern>
    </servlet-mapping>

这里,我们解析Json用的是fastjson,需要找到并下载fastjson的jar文件,复制到工程的lib目录(由于我们在建立工程的时候,已经将lib目录添加为依赖目录,所以这里直接将jar包复制过来即可)。
Servlet代码中,首先获得上送的Json报文,然后,解析出其中的查询条件,最后,根据查询条件查找指定的结果,并返回。服务端代码如下:

package com.web.test;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by chengxia on 2018/12/3.
 */
public class JsonServletParseReqJson extends HttpServlet {
    JSONArray jsonArray = JSONArray.parseArray("[{\"name\":\"Kobe\", \"team\":\"Lakers\"},{\"name\":\"Tim\", \"team\":\"Spurs\"},{\"name\":\"Tim\", \"team\":\"Spurs\"}]");
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();//only get input stream once per request.
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } finally {
            reader.close();
        }
        System.out.println("This is request Content:\n" + sb.toString());

        JSONObject reqJsonObj = JSONObject.parseObject(sb.toString());
        System.out.println("Converted to Json: " + reqJsonObj);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        String qryByStr = reqJsonObj.getString("qry_by");
        String qryVal = reqJsonObj.getString(qryByStr);
        System.out.println("Query: " + qryByStr + "=" + qryVal);

        int i;
        //find the json result
        for(i = 0; i < jsonArray.size(); i++){
            if (jsonArray.getJSONObject(i).get(qryByStr).equals(qryVal)){
                break;
            }
        }

        PrintWriter out = response.getWriter();
        if(i >= jsonArray.size()){
            out.print("No result Found.");
        }else{
            out.print(jsonArray.getJSONObject(i));
        }
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }
}

客户端发送请求的代码和前面一样,如下:

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by chengxia on 2018/12/4.
 */
public class HttpURLConnectionDemo {
    public String doPost(String URL){
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try{
            URL url = new URL(URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //发送POST请求必须设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            //获取输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Kobe\"}";
            out.write(jsonStr);
            out.flush();
            out.close();
            //取得输入流,并使用Reader读取
            if (200 == conn.getResponseCode()){
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null){
                    result.append(line);
                    System.out.println(line);
                }
            }else{
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
        }
        return result.toString();
    }

    public static void main(String[] args) throws Exception {
        HttpURLConnectionDemo http = new HttpURLConnectionDemo();
        System.out.println("\nTesting 2 - Do Http POST request");
        http.doPost("http://localhost:8080/jsonreq");

    }

}

3、运行结果

在第一个服务端程序的工程中启动服务器,然后,在另一个工程中运行客户端发送请求的代码,结果如下。
在服务器端工程的控制台输出:

This is request Content:
{"qry_by":"name", "name":"Kobe"}

Converted to Json: {"name":"Kobe","qry_by":"name"}
Query: name=Kobe

在发送请求工程的控制台中输出:

Testing 2 - Do Http POST request
{"name":"Kobe","team":"Lakers"}

Process finished with exit code 0

参考

上一篇 下一篇

猜你喜欢

热点阅读