I'm using this code for fetching data from a URL using AsyncTask
:
protected String doInBackground(Object... params) {
int ResponseCode=-1;
try {
URL myURL=new URL("URL...");
HttpURLConnection connection=(HttpURLConnection) myURL.openConnection();
connection.connect();
ResponseCode=connection.getResponseCode();
if (ResponseCode==HttpURLConnection.HTTP_OK) {
InputStream inputStream=connection.getInputStream();
Reader reader=new InputStreamReader(inputStream);
int contentLength=connection.getContentLength();
char[] charArray=new char[contentLength];
reader.read(charArray);
String responseData=new String(charArray);
Log.i("TAG", responseData);
Log.i("TAG", ""+contentLength);
}
else {
Log.i("TAG", " Unsuccessful HTTP Response Code: "+ResponseCode);
}
}catch (MalformedURLException e) {
Log.i("TAG", "MalformedURLException Error: "+e.getMessage());
} catch (IOException e) {
Log.i("TAG", "IOException Error: "+e.getMessage());
} catch (Exception e) {
Log.i("TAG", "Exception Error: "+e);
}
return " "+ResponseCode;
}
above code works fine and I use it in some projects, but for URL that I'm working on, it doesn't work and always return -1 for Response Code
,because the HTTP response of my URL doesn't contain Content-Length
header, the content is chunked., now I wanna know Is there any equivalent way to do that?
Thanks in advanced
finally I solved my problem this way :
try {
URL blogPostURL=new URL("URL...");
URLConnection connection=blogPostURL.openConnection();
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseData;
while ((responseData = reader.readLine()) != null){
Log.i("TAG", responseData);
}
reader.close();
}catch (MalformedURLException e) {
Log.i("TAG", "MalformedURLException Error: "+e.getMessage());
} catch (IOException e) {
Log.i("TAG", "IOException Error: "+e.getMessage());
} catch (Exception e) {
Log.i("TAG", "Exception Error: "+e);
}