我有一个网络服务,其内容类型为 application/vnd.oracle.adf.resourceitem json 。
通过达到此服务获得的回复源的httpentity看起来像是这样
ResponseEntityProxy{[Content-Type: application/vnd.oracle.adf.resourceitem+json,Content-Length: 3,Chunked: false]}
当我尝试将此httpentity转换为字符串时,它会给我一个空白的字符串{}
。
以下是我尝试将HttpEntity
转换为String
1。
String strResponse = EntityUtils.toString(response.getEntity());
2。
String strResponse = "";
String inputLine;
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
try {
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
strResponse += inputLine;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
3。
response.getEntity().writeTo(new FileOutputStream(new File("C:\Users\harshita.sethi\Documents\Chabot\post.txt")));
所有返回字符串 -> {}
。
谁能告诉我我在做什么错?
这是因为内容类型吗?
上面的代码仍在使用空的JSON对象给出相同的响应。因此,我修改了以下代码。这似乎很好。
URL url = new URL(urlString);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.addRequestProperty("Authorization", getAuthToken());
con.addRequestProperty("Content-Type", "application/vnd.oracle.adf.resourceitem+json;charset=utf-8");
String input = String.format("{"%s":"%s","%s":"%s"}", field, value, field2, value2);
System.out.println(input);
OutputStream outputStream = con.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
con.connect();
System.out.println(con.getResponseCode());
// Uncompressing gzip content encoding
GZIPInputStream gzip = new GZIPInputStream(con.getInputStream());
StringBuffer szBuffer = new StringBuffer();
byte tByte[] = new byte[1024];
while (true) {
int iLength = gzip.read(tByte, 0, 1024);
if (iLength < 0) {
break;
}
szBuffer.append(new String(tByte, 0, iLength));
}
con.disconnect();
returnString = szBuffer.toString();
身份验证方法
private String getAuthToken() {
String name = user;
String pwd = this.password;
String authString = name + ":" + pwd;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
System.out.println(new String(authEncBytes));
return "Basic " + new String(authEncBytes);
}
如果任何人都面临同一问题。让我分享我面临的挑战以及如何纠正这些挑战。
上面的代码适用于所有内容类型/方法。可用于任何类型(GET,POST,PUT,DELETE(。对于我的要求,我有一个
的邮政网络服务内容编码→GZIP
content-type→应用程序/vnd.oracle.adf.resourceitem json
挑战:我能够获得正确的响应代码,但我的垃圾字符是我的响应字符串。
解决方案:这是因为以gzip
格式压缩了输出,需要不压缩。
上面也提到了 gzip content encoding
的不压缩的代码。
希望它可以帮助未来的用户。