首页 > 解决方案 > 如何以纯文本/字符串而不是 JSON 格式读取响应

问题描述

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

在此处输入图像描述
我有响应,但我不知道如何在我的代码中将其转换为字符串。
下面是我尝试但失败的代码。

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();
        }

标签: androidretrofithttpresponse

解决方案


您可以使用 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();
}

推荐阅读