目前,我正致力于使用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();
}
}