Reputation: 370
I want to read these simple numbers which is a response from an HTTP API.
I have the response but I have no idea how do I convert it to string in my code.
below is the code I tried but failed.
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();
}
Upvotes: 2
Views: 1565
Reputation: 183
Try this code.
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;
}
Upvotes: 1
Reputation: 484
You can use java http/https URL connection to get the response from the input stream.
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();
}
Upvotes: 3