我正在使用REST API,该API返回连续的实时流式响应主体。响应体流一直在打开。我想通过Apache Http Components阅读流式响应。
感谢您的帮助。
[UPDATE] 我的回应与此演示类似 https://github.com/brianhempel/stream_json_demo
答案 0 :(得分:0)
您必须设置一个客户端以从API发送和接收流响应。
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost/something");
post.setHeader("Referer", "http://localhost/something");
post.setHeader("Authorization", "Basic (with a username and password)");
post.setHeader("Content-type", "application/json");
// if you need any parameters
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("paramName", "paramValue"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
Header encodingHeader = entity.getContentEncoding();
// you need to know the encoding to parse correctly
Charset encoding = encodingHeader == null ? StandardCharsets.UTF_8 :
Charsets.toCharset(encodingHeader.getValue());
// use org.apache.http.util.EntityUtils to read json as string
String json = EntityUtils.toString(entity, StandardCharsets.UTF_8);
JSONObject o = new JSONObject(json);
您可以从http://hc.apache.org/和commons-io那里获得apache HTTP客户端库