如何在java中通过HTTP更快地下载和解析JSON字符串

时间:2015-06-08 09:45:21

标签: java json parsing io httpurlconnection

目前,我正致力于使用HttpURLConnection通过http进行通信的调优客户端/服务器应用程序。

此处,客户端将java-serializable object作为请求发送给服务器(HttpServlet收到此消息)并收到JSON字符串作为响应。

然后将JSON响应转发给JSON解析器进行处理。

以前,首先我们下载并构建了通过JSON的完整stream字符串,然后我们将其转发给解析器。然后我将其调整为将stream it-self转发给解析器(Jackson Streaming parser)并让它处理它收到的部分而无需等待下载整个JSON字符串。

当下载速度良好时,这会产生良好的效果。但是在这里,我在一个环境中得不到那么好的结果,因为下载时间太长,处理速度非常快。 (有时17(s)下载4-5MB JSON字符串)。

如何调整它以便比这更快地下载和解析JSON?

客户端

URL url = new URL(http://myhost.com/Connectors/url2Service);
HttpURLConnection servletConnection = (HttpURLConnection) url.openConnection();

servletConnection.setDoInput(true);  
servletConnection.setDoOutput(true);  
servletConnection.setUseCaches (false);  
servletConnection.setDefaultUseCaches (false);  
servletConnection.setRequestMethod("POST");
servletConnection.setRequestProperty("content-type","application/x-java-serialized-object");
servletConnection.setRequestProperty("Accept","application/json");
servletConnection.setRequestProperty("Accept-Encoding","gzip,deflate");
servletConnection.setRequestProperty("user-agent","Mozilla(MSIE)");
servletConnection.setConnectTimeout(30000);
servletConnection.setReadTimeout(60000);
servletConnection.connect();


String encodingHeader = servletConnection.getHeaderField("Content-Encoding");

String contentType = servletConnection.getHeaderField("content-type");

if(contentType.equals("application/json")){

    InputStream inputStream = servletConnection.getInputStream();

    if(encodingHeader != null && encodingHeader.toLowerCase().indexOf("gzip") != -1) {

        gzipis = new GZIPInputStream(inputStream);

    } else {

        iSR = new InputStreamReader(inputStream);
        br = new BufferedReader(iSR);

    }

    ResposeObject resposeObject = new JsonString2ResposeObject().parse(gzipis); // previously we passed complete String here
}

服务器

public class url2Service extends HttpServlet{

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
            RequestObject requestObject = (RequestObject) ois.readObject();

            response.setContentType("application/json");

            String jsonResponseString = new ServerApplication().doMoreWithRequest(requestObject);

            OutputStreamWriter wr = null;

            if (null != aEncoding && aEncoding.toLowerCase().indexOf("gzip") != -1) {
                gzipos = new GZIPOutputStream(response.getOutputStream());
                wr = new OutputStreamWriter(gzipos);                    
                response.addHeader("Content-Encoding", "gzip,deflate");                 
            } else {
                wr = new OutputStreamWriter(response.getOutputStream());
            }

            wr.write(jsonString);
            wr.flush();
    }

}

0 个答案:

没有答案