如何将HttpURLConnection.getInputStream()转换为该类作为响应?

时间:2019-01-22 08:19:27

标签: json servlets

我使用下面的代码将请求转发到另一台服务器,然后我想将响应转换为JSON格式的特定类,但是得到的响应是com.mydomain.models.Result@f87ad6,下一步我该怎么做?

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    final HttpServletResponse response = (HttpServletResponse) res;
    conn = (HttpURLConnection) url.openConnection();
    ...
    Boolean isGzip = "gzip".equals(conn.getContentEncoding());
    InputStream in = conn.getInputStream();
    if (isGzip) {
        in = new GZIPInputStream(in);
    }
    JSONObject resData = (JSONObject) new JSONParser().parse(new InputStreamReader(in, "UTF-8"));
    Result<String> result = new Result<String>();
    result.setData(resData.toJSONString());
    pipe(new ByteArrayInputStream(result.toString().getBytes("UTF-8")), response.getOutputStream());
    ...
}

private void pipe(InputStream in, OutputStream out) {
    int b = -1;
    try {
        while ((b = in.read()) > -1) {
            out.write(b);
        }
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
...
public class Result<T> {
    priavte String status;
    private T data;
    ...
}

0 个答案:

没有答案