gpt4 book ai didi

java - Android - HTTP 响应的字符大小

转载 作者:行者123 更新时间:2023-12-01 09:57:04 25 4
gpt4 key购买 nike

我不是专业开发 Android 的人。我想从我的服务器下载一个 JSON 对象,但我只能找到这样的代码:

    private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;

try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("ServerConnection", "The response is: " + response);
is = conn.getInputStream();;
//is.
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;

// Makes sure that the InputStream is closed after the app is
// finished using it.
} catch (MalformedURLException e) {
//
return "error";
} catch (IOException e) {
//
return "error";
} finally {
if (is != null) {
is.close();
}
}
}

它工作正常,我无法理解。但它有一个 int len = 500,并且我返回的 json 被裁剪为 500 个字符。我尝试更改为一个很大的数字,但它在末尾添加了空格。我如何知道 InputSteam 包含的字符串的字符大小?

谢谢

最佳答案

您可以检查响应的 Content-Length header 值:

Map<String, List<String>> headers = connection.getHeaderFields();
for (Entry<String, List<String>> header : headers.entrySet()) {
if(header.getKey().equals("Content-Legth")){
len=Integer.parseInt(header.getValue());
}
}

或者您可以在缓冲阅读器中做出响应,如下所示:

InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int c = 0;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}

关于java - Android - HTTP 响应的字符大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37119613/

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