Android 如何以纯文本/字符串而不是JSON读取响应
我想阅读这些简单的数字,这是来自HTTP API的响应 我有响应,但我不知道如何在代码中将其转换为字符串。 下面是我尝试但失败的代码Android 如何以纯文本/字符串而不是JSON读取响应,android,retrofit,httpresponse,Android,Retrofit,Httpresponse,我想阅读这些简单的数字,这是来自HTTP API的响应 我有响应,但我不知道如何在代码中将其转换为字符串。 下面是我尝试但失败的代码 try { //Prepare Connection myURL = new URL(url); myURLConnection = myURL.openConnection(); myURLConnection.connect(); //re
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();
}
试试这个代码
private static String readServerResponse(HttpURLConnection connection) {
// read the output from the server
String response = null;
BufferedReader reader = null;
InputStreamReader inputStreamReader = null;
try {
StringBuilder stringBuilder = new StringBuilder();
InputStream responseStream = connection.getErrorStream();
if (responseStream == null) {
responseStream = connection.getInputStream();
}
inputStreamReader = new InputStreamReader(responseStream);
reader = new BufferedReader(inputStreamReader);
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append('\n');
}
response = stringBuilder.toString();
} catch (Throwable t) {
Log.i(LOG_TAG, "Could not read connection response from: " + connection.getURL().toString(), t);
} finally {
try {
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
} catch (Throwable ignore) {
}
}
return response;
}
运行代码时,我会得到android.os.NetworkOnMainThreadException。您需要在线程内调用此方法或使用异步任务进行后台操作。按照下面的链接使用Asynctask。嘿@RaunakPandey,让我知道它是否有效。我最终通过截击成功了:是的,你可以使用网络库进行截击或改装。