gpt4 book ai didi

java - JSON: "Unexpected character (<) at position 0"

转载 作者:行者123 更新时间:2023-11-30 09:15:07 26 4
gpt4 key购买 nike

这是获取 channel 摘要的 twitch.tv api 请求:http://api.justin.tv/api/streams/summary.json?channel=mychannel .如果我通过浏览器发布它,我会得到正确的结果。但在结果解析过程中,我以编程方式收到异常。

我使用 apache HttpClient 发送请求和接收响应。和JSON——简单解析JSON内容。

这就是我尝试根据 api 从响应中获取 JSON 的方式:

HttpClient httpClient = HttpClients.createDefault();
HttpGet getRequest = new HttpGet(new URL("http://api.justin.tv/api/streams/summary.json?channel=mychannel").toURI());
getRequest.addHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);

BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String output;
StringBuilder builder = new StringBuilder();
while((output = br.readLine()) != null) {
builder.append(output);
}
br.close();

JSONParser parser = new JSONParser();
Object obj = parser.parse(builder.toString()); //Exception occurs here

预期结果:{"average_bitrate":0,"viewers_count":"0","streams_count":0} ,但执行上述示例会导致:Unexpected character (<) at position 0.

如何从响应中获取 JSON 正文?浏览器正确显示结果。

最佳答案

试试这个:

        URL url = new URL("http://api.justin.tv/api/stream/summary.json?channel=mychannel");
HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
request1.setRequestMethod("GET");
request1.connect();
InputStream is = request1.getInputStream();
BufferedReader bf_reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = bf_reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
String responseBody = sb.toString();
JSONParser parser = new JSONParser();
Object obj = parser.parse(responseBody);
System.out.println(obj);

关于java - JSON: "Unexpected character (<) at position 0",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20070380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com