gpt4 book ai didi

java - 如何从HTTP请求中获取正确的数据

转载 作者:行者123 更新时间:2023-12-01 20:17:57 28 4
gpt4 key购买 nike

我正在尝试使用 Java 中的 GET 方法使用简单的 HTTP 请求从 stackoverflow api 获取用户信息。

我之前使用过这段代码,使用 GET 方法获取另一个 HTTP 数据,没有出现任何问题:

    URL obj;
StringBuffer response = new StringBuffer();
String url = "http://api.stackexchange.com/2.2/users?inname=HCarrasko&site=stackoverflow";
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}

in.close();
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

但在这种情况下,当我打印 response var 时,我得到的只是陌生的符号,如下所示:

�mRM��0�+�N!���FZq�\�pD�z�:V���JX���M��̛yO^���뾽�g�5J&� �9�YW�%c`do���Y'��nKC38<A�&It�3��6a�,�,]���`/{�D����>6�Ɠ��{��7tF ��E��/����K���#_&�yI�a�v��uw}/�g�5����TkBTķ���U݊c���Q�y$���$�=ۈ��ñ���8f�<*�Amw�W�ـŻ��X$�>'*QN�?�<v�ݠ FH*��Ҏ5����ؔA�z��R��vK���"���@�1��ƭ5��0��R���z�ϗ/�������^?r��&�f��-�OO7���������Gy�B���Rxu�#:0�xͺ}�\�����

提前致谢。

最佳答案

内容可能是 GZIP 编码/压缩的。以下是我在所有使用 HTTP 的基于 Java 的客户端应用程序中使用的通用片段,旨在解决这个问题:

// Read in the response
// Set up an initial input stream:
InputStream inputStream = fetchAddr.getInputStream(); // fetchAddr is the HttpURLConnection

// Check if inputStream is GZipped
if("gzip".equalsIgnoreCase(fetchAddr.getContentEncoding())){
// Format is GZIP
// Replace inputSteam with a GZIP wrapped stream
inputStream = new GZIPInputStream(inputStream);
}else if("deflate".equalsIgnoreCase(fetchAddr.getContentEncoding())){
inputStream = new InflaterInputStream(inputStream, new Inflater(true));
} // Else, we assume it to just be plain text

BufferedReader sr = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuilder response = new StringBuilder();
// ... and from here forward just read the response...

这依赖于以下导入:java.util.zip.GZIPInputStream ; java.util.zip.Inflater ;和java.util.zip.InflaterInputStream .

关于java - 如何从HTTP请求中获取正确的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45449642/

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