gpt4 book ai didi

android - 如何以纯文本/字符串而不是 JSON 格式读取响应

转载 作者:行者123 更新时间:2023-12-05 00:19:36 26 4
gpt4 key购买 nike

我想阅读这些简单的数字,它们是来自 HTTP API 的响应。

enter image description here
我有响应,但我不知道如何在我的代码中将其转换为字符串。
下面是我尝试但失败的代码。

try {
//Prepare Connection
myURL = new URL(url);
myURLConnection = myURL.openConnection();
myURLConnection.connect();
//reading response
reader= new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
while ((response = reader.readLine()) != null)
//print response
Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show();

//finally close connection
reader.close();
}
catch (IOException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), ""+e.toString(), Toast.LENGTH_SHORT).show();
}

最佳答案

您可以使用 java http/https URL 连接从输入流中获取响应。

String getText(String url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
//add headers to the connection, or check the status if desired..

// handle error response code it occurs
int responseCode = conn.getResponseCode();
InputStream inputStream;
if (200 <= responseCode && responseCode <= 299) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}

BufferedReader in = new BufferedReader(
new InputStreamReader(
inputStream));

StringBuilder response = new StringBuilder();
String currentLine;

while ((currentLine = in.readLine()) != null)
response.append(currentLine);

in.close();

return response.toString();
}

关于android - 如何以纯文本/字符串而不是 JSON 格式读取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62451108/

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