I have searched couple of titles about this but I couldn't get a proper way what I want to do. I want to connect a server with GET url and must read return xml file into a string that I can use in different activities. My code is working just fine when I debug it but I couldn't get a proper string return from it.
protected JSONArray doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
JSONArray response = new JSONArray();
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpStatus.SC_OK){
String responseString = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", responseString);
response = new JSONArray(responseString);
}else{
Log.v("CatalogClient", "Response code:"+ responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(urlConnection != null)
urlConnection.disconnect();
}
return response;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}