gpt4 book ai didi

java - HttpURLConnection 仅返回几个字节

转载 作者:行者123 更新时间:2023-12-01 19:19:27 24 4
gpt4 key购买 nike

我有:

InputStream input = null;
HttpURLConnection connection = null;
URL url = new URL("...");

connection = (HttpURLConnection) url.openConnection();
String zam = "...";
connection.setRequestProperty("Cookie",zam);
connection.connect();

int fileLength = connection.getContentLength();
input = connection.getInputStream();
byte data[] = new byte[400];
int count;
count = input.read(data);
connection.disconnect();
String str1 = new String(data);

str1,响应始终只有:

!DOCTYPE HTML PUBLIC "-/

仅此而已。但是当我关闭cookie时:

connection.setRequestProperty("Cookie",zam);

一切正常;

感谢 ind adv 的回复。阿迪。

最佳答案

我猜问题是你没有从流中读取所有数据。尝试使用这样的方法。

public static String streamToString(final InputStream is, final int bufferSize) throws Exception {
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try (Reader in = new InputStreamReader(is, "UTF-8")) {
int rsz = 0;
while ((rsz = in.read(buffer, 0, buffer.length)) > 0) {
out.append(buffer, 0, rsz);
}
}
return out.toString();
}

还可以阅读有关其他方法的答案 How do I read / convert an InputStream into a String in Java?

关于java - HttpURLConnection 仅返回几个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59378483/

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