我有这种情况:有一个通过HTTPS运行的Jersey rest Web服务。我正在研究一个将Json张贴到该服务并读取响应的Android代码。我设法通过API日志进行连接,我可以看到已收到调用并且未显示任何错误,我还在连接的“ InputStream”中获取了数据,但是数据已加密!即使我尝试使用纯HTTP连接并以HTTP模式运行Web服务,结果也是相同的。
让我感到困惑的是,相等的cURL请求会产生正确的输出而没有任何问题...我错在哪里?这是我正在使用的代码:
URL url = new URL("https://myServer:8780/api/<apicall>");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// Create the SSL connection
SSLContext sc;
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new java.security.SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());
// set Timeout and method
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setRequestProperty("Accept-Encoding", "gzip");
conn.setRequestProperty("Accept", "application/json");
// Add any data you wish to post here
String json = "{\"test\":\"hello\"}";
byte[] bytes = json.getBytes("UTF-8");
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.flush();
out.close();
String result = new String();
InputStream is = null;
/*if ("gzip".equals(conn.getContentEncoding()))
is = new GZIPInputStream(conn.getInputStream()); THIS WOULD FAIL WITH ERROR MESSAGE THAT CONTENT IS NOT IN GZIP FORMAT!
else*/
is = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}
与此同时,此cURL调用(我正在使用Linux)可以正常工作,并从服务器返回预期的JSON响应:
curl -H 'Accept-Encoding: gzip' -X POST https://myServer:8780/api/<apicall> -d '{"test":"hello"}'
编辑问题是由我的服务器同时使用“内容编码:gzip”和“传输编码:gzip”引起的。当我删除“传输编码”问题后,就解决了!