内容类型application/vnd.oracle.adf.resourceitem+json的阅读休息服务

Reading rest service of content type application/vnd.oracle.adf.resourceitem+json

我有一个内容类型为 application/vnd.oracle.adf.resourceitem+json 的网络服务。

点击这个服务得到的reponse的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")));

所有 returns 个字符串 -> {}

谁能告诉我我做错了什么?

这是内容类型的问题吗?

上面的代码仍然给出与空 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);
    }

以防有人遇到同样的问题。让我分享一下我面临的挑战以及我是如何纠正这些挑战的。

以上代码适用于所有 content-types/methods。可用于任何类型(GET、POST、PUT、DELETE)。 根据我的要求,我有一个 POST 网络服务

内容编码 →gzip

内容类型→application/vnd.oracle.adf.resourceitem+json

挑战:我能够获得正确的响应代码,但我得到的响应字符串是垃圾字符。

解决方法: 这是因为输出压缩为gzip格式,需要解压

解压gzip content encoding的代码上面也有提到

希望对以后的用户有所帮助。