当前位置 : 首页 » 文章分类 :  开发  »  Apache-HttpComponents

Apache-HttpComponents

Apache HttpComponents笔记

官网
http://hc.apache.org/

从 HTTPResponse 中读取Json

利用 BufferedReader.readLine() 从 HTTPResponse.getEntity().getContent() 流中逐行读取返回内容:

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
    builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);

如果JSON实际上是一行,那么你也可以删除循环和builder:

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);

使用gson:

void getJson() throws IOException {
    HttpClient  httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("some url of json");
    HttpResponse httpResponse = httpClient.execute(httpGet);
    String response = EntityUtils.toString(httpResponse.getEntity());

    Gson gson = new Gson();
    MyClass myClassObj = gson.fromJson(response, MyClass.class);
}

使用实例:

HttpResponse httpResponse = UdsHttpClient.postForRawResponseWithHeader(server + QUERY_SO_ORDER_LIST_API, null, content, false, headersMap, logger);
checkState(httpResponse != null, "Artemis returned empty response");
checkState(httpResponse.getStatusLine() != null, "Artemis return error response");
checkState(httpResponse.getEntity() != null, "Artemis returned empty response entity");
checkState(httpResponse.getStatusLine().getStatusCode() != ARTEMIS_TOKEN_ERROR_CODE, "Artemis return token error code");
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String result = reader.readLine();
QuerySOListResponse response = JSONUtils.readValue(result, QuerySOListResponse.class);

How do I parse JSON from a Java HTTPResponse?
https://stackoverflow.com/questions/2845599/how-do-i-parse-json-from-a-java-httpresponse

如何从Java HTTPResponse解析JSON?
https://codeday.me/bug/20170629/34297.html

上一篇 Apache-kafka

下一篇 Java-枚举Enum

阅读
278
阅读预计2分钟
创建日期 2018-08-24
修改日期 2018-08-24
类别
标签
百度推荐