android - 如何以纯文本/字符串而不是 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();
}
解决方案
您可以使用 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();
}
推荐阅读
- autodesk-forge - Autodesk Forge - 文档管理“描述”和“集”信息可用性
- haskell - 没有因使用“道具”而产生的(任意自然)实例
- vb.net - how to properly remove files added under "My Project" in solution explorer?
- python - How to display number of rows with only lower case characters
- haskell - 无法将预期类型与 Haskell 中的实际类型匹配
- javascript - 填充时返回 {} 的 Javascript 对象
- python - 使用带有“saga”求解器和“elasticnet”惩罚的 sklearn 的 LogisticRegression
- python - Python无法获取json值
- python - 删除 Pandas 列中的项目符号字符
- python - 在 for 循环中更新变量