响应json:
{
"filename": "vcops-6.0.0-MPforAWS-1.1-1695068.pak",
"links": [
{
"rel": "pak_information",
"href": "https://<IP>:443/casa/upgrade/cluster/pak/MPforAWS-600/information"
},
{
"rel": "pak_file_information",
"href": "https://<IP>:443/casa/upgrade/slice/pak/MPforAWS-600/file_information"
},
{
"rel": "pak_cluster_status",
"href": "https://<IP>:443/casa/upgrade/cluster/pak/MPforAWS-600/status"
}
],
"pak_id": "MPforAWS-600"
}
我正在使用我们拥有的框架的一个帮助器. Framework将响应返回为“InputStream”.
我想从这个“InputStream”获得“pak_id”.我尝试使用inputStreamObj.toString()这对我不起作用.
我使用的方法是:
private String getPakId(InputStream uploadResponse) {
String pakId = null;
try {
String responseString = readInputStream(uploadResponse);
JSONObject jObj = new JSONObject(responseString);
pakId = jObj.getString("pak_id").trim();
Reporter.log("Pak id is=" + pakId, true);
} catch (Exception e) {
Reporter.log("Error in getting pak_id " + e.getMessage(), true);
}
return pakId;
}
和
private String readInputStream(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "UTF-8"));
String tmp;
StringBuilder sb = new StringBuilder();
while ((tmp = reader.readLine()) != null) {
sb.append(tmp).append("\n");
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
sb.setLength(sb.length() - 1);
}
reader.close();
return sb.toString();
}
最佳答案 如果您查看
InputStream的文档,您会发现它不会向您保证toString将向您显示流的内容.
如果你对实际流式传输不感兴趣(如果你希望响应很小,这是合理的,就像这里的情况一样),可以先从流中获取所有字节,然后将它们放入String,然后解析String.
为了从InputStream中获取String,我建议从apache commons-io开始使用IOUtils.toString.