Error on executing HTTP request in android - android

I know it may seems to dumb question and there are lots of such questions but I have problems but I can't figure it out what does errors in log means. I know these http methods are deprecated and I should replace them, but I want to get response now. This is my code:
try
{
response = httpClient.execute(httpRequest);
responseCode = response.getStatusLine().getStatusCode();
responsePhrase = response.getStatusLine().getReasonPhrase();
HttpEntity responseEntity = response.getEntity();
if(responseEntity != null)
{
InputStream is = responseEntity.getContent();
responseString = convertStreamToString(is);
try
{
is.close();
} catch (Exception ignored) { }
}
else
return "";
}
catch (IOException e)
{
onError(e);
}
The codes goes to catch block when it tries to run httpClient.execute and the e object is null. This is log:
10-17 18:07:19.404 21766-21766/? E/Mms/ipmsg/compose﹕ saveIpMessageDraft(): mIpMessageDraft is null!
java.lang.Exception
at com.android.mms.ui.ComposeMessageActivity.saveIpMessageDraft(ComposeMessageActivity.java:13622)
at com.android.mms.ui.ComposeMessageActivity.onSaveInstanceState(ComposeMessageActivity.java:3870)
at android.app.Activity.performSaveInstanceState(Activity.java:1147)
at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1291)
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3336)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3402)
at android.app.ActivityThread.access$900(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
I couldn't figure it out what errors are. I searched through web I couldn't find anything about saveIpMessageDraft or mIpMessageDraft. What is wrong with my code?

Related

How to get integer from json object async in android?

Original Question -
I was following a tutorial on json in android, but having problem to get json value using Async in android. First I created jsonparser class and added following to it -
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
// Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
// Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Then to use this in fragment by async i tried -
class getTopicId extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Topic of the Day ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl("http://medicalguru.in/android/tod.php");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
topic_id = json.getInt("value");
}
catch (JSONException e) {
e.printStackTrace();
}
finally {
Toast.makeText(getActivity(), "topic id -"+topic_id, Toast.LENGTH_LONG).show();
}
}
}
but the app is crashing when i execute this async.
my logcat shows -
03-06 15:07:03.123: E/AndroidRuntime(2041): FATAL EXCEPTION: main
03-06 15:07:03.123: E/AndroidRuntime(2041): java.lang.NullPointerException
03-06 15:07:03.123: E/AndroidRuntime(2041): at in.medicalguru.DailyTestFragment$getTopicId.onPostExecute(DailyTestFragment.java:786)
03-06 15:07:03.123: E/AndroidRuntime(2041): at in.medicalguru.DailyTestFragment$getTopicId.onPostExecute(DailyTestFragment.java:1)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.os.AsyncTask.finish(AsyncTask.java:631)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.os.Handler.dispatchMessage(Handler.java:99)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.os.Looper.loop(Looper.java:137)
03-06 15:07:03.123: E/AndroidRuntime(2041): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-06 15:07:03.123: E/AndroidRuntime(2041): at java.lang.reflect.Method.invokeNative(Native Method)
03-06 15:07:03.123: E/AndroidRuntime(2041): at java.lang.reflect.Method.invoke(Method.java:525)
03-06 15:07:03.123: E/AndroidRuntime(2041): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-06 15:07:03.123: E/AndroidRuntime(2041): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-06 15:07:03.123: E/AndroidRuntime(2041): at dalvik.system.NativeStart.main(Native Method)
The link mentioned above in the code outputs as -
{"value":1}
when opened normally, but when I run in async it says err related to nullpointer?
Couldn't figure, where I am making mistake ?
Edit 1 :
*tod.php* code (Since Matthew has pointed something which I dont understand, so it may be helpful)
<?php
$today = date("Ymd");
switch($today){
case 20140304 :
$tod["value"] = 24;
break;
case 20140305 :
$tod["value"] = 25;
break;
case 20140306 :
$tod["value"] = 1;
break;
default:
$tod["value"] = 1;
break;
}
echo json_encode($tod);
?>
Edit 2 : *Found the problem (fully for me) but Partly in Real* - A special thanks to Matthew for his idea, to uncomment the error logs of function getJSONFromUrl(String url). I got a new error line in logcat -
Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject
After little bit of search on google and stacksoverflow I found one suggestion to change chrSet to UTF-8 instead of iso-8859-1. and it worked for my requested url in both situations (with or without WWW - suggestion to test, by nikis). But this answer is partial real, because, now 2 unanswered questions developed -
1. Why did chrSet change worked? In future, what chrSet to be used, to avoid this problem, and what's the use of other one chrSet?
2. Matthew has replicated my Json to his server mwesly.com/test/ . Trial on his server, logcat shows following error in all cases (with or without WWW, with or without using index.php in the end) -
Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Now, why is this error appearing on his server? What should be done to prevent/treat this error.
If I need to ask these updated questions separately, please let me know.
It looks like json is null on following line, which is giving you the NullPointerException.
topic_id = json.getInt("value");
I think this is because your parser is having issues parse the json. I wrote a quick python script and tried to parse the page and it failed as well. For some reason, the response I get from http://medicalguru.in/android/tod.php is:
\xef\xbb\xbf{"value":1}
I am not sure why the \xef\xbb\xbf bytes are there, but they are likely causing the problem.
edit: a quick google search says it is the UTF-8 BOM. If you remove it your android code should work.
edit2: I put an example json on http://mwesly.com/test. Try hitting that json to see if your android code is correct. If it works, it means there is a problem with your endpoint, not your android code.
edit3: example of using loopj:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://mwesly.com/test", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject json) {
// do something with the json
int value = json.getInt("value");
}
});
I'm going to head to bed, if you still haven't solved this problem when I wake up, I'll give it another look. Good luck and happy coding!
Try to use the following getJSONFromUrl method:
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
return new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private JSONObject jObj = null;
private JSONArray JArr = null;
and then after;
URL url = null;
try {
url = new URL("your url is here");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONParser jParser = new JSONParser();
String json_value = jParser.getJSONFromUrl(url);
try {
JArr = new JSONArray(json_value);
} catch (JSONException e) {
e.printStackTrace();
}
jObj = null;
for (int i = 0; i < JArr.length(); i++) {
try {
jObj = JArr.getJSONObject(i);
topic_id = jObj.getInt("value");
} catch (JSONException e) {
e.printStackTrace();
}
}

java.io.IOException: Received authentication challenge is null in ICS 4.0.3

I'm trying to logoff from the server. But it returns "0" response code with this exception. I'm using GET verb to do this.
LogCat
10-17 14:54:13.261: W/System.err(868): java.io.IOException: Received authentication challenge is null
10-17 14:54:13.284: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:397)
10-17 14:54:13.284: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:345)
10-17 14:54:13.304: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:276)
10-17 14:54:13.324: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:479)
10-17 14:54:13.324: W/System.err(868): at com.remote.synchronizer.haris.CustomHttpClient.executeGet(CustomHttpClient.java:131)
10-17 14:54:13.354: W/System.err(868): at com.remote.synchronizer.haris.OptionsActivity$1$3$1.run(OptionsActivity.java:87)
10-17 14:54:13.364: W/System.err(868): at android.os.Handler.handleCallback(Handler.java:605)
10-17 14:54:13.384: W/System.err(868): at android.os.Handler.dispatchMessage(Handler.java:92)
10-17 14:54:13.384: W/System.err(868): at android.os.Looper.loop(Looper.java:137)
10-17 14:54:13.404: W/System.err(868): at android.app.ActivityThread.main(ActivityThread.java:4424)
10-17 14:54:13.424: W/System.err(868): at java.lang.reflect.Method.invokeNative(Native Method)
10-17 14:54:13.424: W/System.err(868): at java.lang.reflect.Method.invoke(Method.java:511)
10-17 14:54:13.454: W/System.err(868): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-17 14:54:13.474: W/System.err(868): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-17 14:54:13.474: W/System.err(868): at dalvik.system.NativeStart.main(Native Method)
10-17 14:54:13.484: E/HTTP Response(868): java.io.IOException: Received authentication challenge is null
CustomHttpClient.java
public class CustomHttpClient {
static HttpClient client = new DefaultHttpClient();
static HttpURLConnection connection = null;
public static int executePost(String url, String postParameters)
{
int response=0;
OutputStream output = null;
try
{
connection = (HttpURLConnection)new URL(url).openConnection();
System.setProperty("http.keepAlive", "false");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.connect();
output = connection.getOutputStream();
output.write(postParameters.getBytes("UTF-8"));
response=connection.getResponseCode();
}
catch(Exception e)
{
e.printStackTrace();
Log.e("HTTP Response", e.toString());
}
finally {
if(connection != null) {
// connection.disconnect();
if (output != null)
try { output.close(); }
catch (IOException logOrIgnore) {}
}
}
return response;
}
public static int executeGet(String url)
{
int response=0;
//HttpURLConnection connection = null;
try
{
connection = (HttpURLConnection) new URL(url).openConnection();
System.setProperty("http.keepAlive", "false");
//connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
response=connection.getResponseCode();
}
catch(Exception e)
{
e.printStackTrace();
Log.e("HTTP Response", e.toString());
}
finally {
if(connection != null) {
// connection.disconnect();
}
}
return response;
}
}
Before this I'm using DefaultHTTPClient in Gingerbird 2.3 its working perfectly but in ICS DefaultHTTPClient is not working so I need to use HttpURLConnection. POST verb is working fine.
You can get the response code after an exception if you call .getResponseCode() a second time on the connection object. This is because the first time you call .getResponseCode() an internal state is set that enables .getResponseCode() to return without throwing an exception.
Example:
HttpURLConnection connection = ...;
try {
// Will throw IOException if server responds with 401.
connection.getResponseCode();
} catch (IOException e) {
// Will return 401, because now connection has the correct internal state.
int responsecode = connection.getResponseCode();
}
I have also answered this question here: https://stackoverflow.com/a/15972969/816017
HttpURLConnection.getResponseCode() throws java.io.IOException: Received authentication challenge is null when it encounters malformed HTTP 401 header. Do you receive WWW-Authenticate and Content-Length headers from server in addition to HTTP/1.1 401 Unauthorized header? See IOException: "Received authentication challenge is null" (Apache Harmony/Android)
If you can't make changes to server, then you can catch that exception (thanks https://stackoverflow.com/a/10904318/262462)
try {
response=connection.getResponseCode();
}
catch (java.io.IOException e) {
if (e.getMessage().contains("authentication challenge")) {
response = HttpsURLConnection.HTTP_UNAUTHORIZED;
} else { throw e; }
}
This error happens beause the server sends a 401 (Unauthorized) but does not give a "WWW-Authenticate" which is a hint for the client what to do next. The "WWW-Authenticate" Header tells the client which kind of authentication is needed (either Basic or Digest). This is usually not very useful in headless http clients, but thats how the standard is defined. The error occurs because the lib tries to parse the "WWW-Authenticate" header but can't.
Possible solutions if you can change the server:
Add a fake "WWW-Authenticate" header like: WWW-Authenticate: Basic realm="fake". This is a mere workaround not a solution, but it should work and the http client is satisfied.
Use HTTP status code 403 instead of 401. It's semantic is not the same and usually when working with login 401 is a correct response (see here for detailed discussion) but its close enough.
Possible solutions if you can't change the server:
As #ErikZ wrote in his post you could use a try&catch
HttpURLConnection connection = ...;
try {
// Will throw IOException if server responds with 401.
connection.getResponseCode();
} catch (IOException e) {
// Will return 401, because now connection has the correct internal state.
int responsecode = connection.getResponseCode();
}
I also posted this here: java.io.IOException : No authentication challenges found

Using AndroidHttpClient will not work

I am trying to use AndroidHttpClient to download a CSV file. For some reason it fails in the line "HttpResponse response httpClient.execute(httpGet, localContext); and simply goes to "finally".
I've checked the URL in my browser - it is working fine.
I get no information from HttpResponse response - it simply like skips it.
I don't get why. Any ideas?
Thanks
D
private ArrayList<String> retrieveStockFinParamsFromYahooApiUri(String yahooApiCall)
{
ArrayList<String> stockFinParamsFromYahooApiUriRows = new ArrayList<String>();
String resultLine = "";
BufferedReader reader = null;
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("yahooGetStockParams");
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(yahooApiCall);
try
{
HttpResponse response = httpClient.execute(httpGet, localContext);
reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
while ((resultLine = reader.readLine()) != null)
{
stockFinParamsFromYahooApiUriRows.add(resultLine);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return stockFinParamsFromYahooApiUriRows;
}
FURTHER INVESTIGATION (05.22.2012):
#Snicolas - thank you for your comments. After I read your comments I thought the problem might originate from the fact that I used the emulator and not my actual device to debug this. I thought the emulator might suffer some connection problems. When I tested it on my device - I noticed the problem still occurred - so this was NOT the problem.
So I change my code to catch (Throwable e) as you advised and got the following stack snapshot:
05-22 18:17:41.457: W/System.err(24552): android.os.NetworkOnMainThreadException
05-22 18:17:41.461: W/System.err(24552): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
05-22 18:17:41.461: W/System.err(24552): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
05-22 18:17:41.461: W/System.err(24552): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
05-22 18:17:41.465: W/System.err(24552): at java.net.InetAddress.getAllByName(InetAddress.java:220)
05-22 18:17:41.465: W/System.err(24552): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-22 18:17:41.465: W/System.err(24552): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-22 18:17:41.468: W/System.err(24552): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-22 18:17:41.468: W/System.err(24552): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-22 18:17:41.468: W/System.err(24552): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-22 18:17:41.472: W/System.err(24552): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-22 18:17:41.472: W/System.err(24552): at android.net.http.AndroidHttpClient.execute(AndroidHttpClient.java:257)
05-22 18:17:41.472: W/System.err(24552): at com.bewildering.app.StournamentDbAdapter$YahooStocksParams.retrieveStockFinParamsFromYahooApiUri(StournamentDbAdapter.java:1536)
05-22 18:17:41.476: W/System.err(24552): at com.bewildering.app.StournamentDbAdapter$YahooStocksParams.run(StournamentDbAdapter.java:1709)
05-22 18:17:41.476: W/System.err(24552): at com.bewildering.app.StournamentActivity.onCreate(StournamentActivity.java:65)
05-22 18:17:41.476: W/System.err(24552): at android.app.Activity.performCreate(Activity.java:4465)
05-22 18:17:41.476: W/System.err(24552): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-22 18:17:41.480: W/System.err(24552): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-22 18:17:41.480: W/System.err(24552): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-22 18:17:41.480: W/System.err(24552): at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-22 18:17:41.484: W/System.err(24552): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-22 18:17:41.484: W/System.err(24552): at android.os.Handler.dispatchMessage(Handler.java:99)
05-22 18:17:41.484: W/System.err(24552): at android.os.Looper.loop(Looper.java:137)
05-22 18:17:41.484: W/System.err(24552): at android.app.ActivityThread.main(ActivityThread.java:4424)
05-22 18:17:41.488: W/System.err(24552): at java.lang.reflect.Method.invokeNative(Native Method)
05-22 18:17:41.488: W/System.err(24552): at java.lang.reflect.Method.invoke(Method.java:511)
05-22 18:17:41.488: W/System.err(24552): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-22 18:17:41.492: W/System.err(24552): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-22 18:17:41.492: W/System.err(24552): at dalvik.system.NativeStart.main(Native Method)
While looking for android.os.NetworkOnMainThreadExceptionI found the documentation which states that this is: The exception that is thrown when an application attempts to perform a networking operation on its main thread.
From that I conclude that I should put my call into an AsyncTask.
Can anyone please confirm that I understand this correctly - or am I missing something here? Strange that I hat to catch (Throwable e) in order to get to the bottom of this.
FURTHER INVESTIGATION (05.22.2012):
I can now confirm that this issue comes due to the fact that The exception... is thrown when an application attempts to perform a networking operation on its main thread. As I read this started with honeycomb.
Ths issue now: I get a 301 response from Yahoo (Moved Permanently). This is strange because when I cut paste the URL into the browser it works.
Any idea why this should work in the browser but not in the application? I must mention that this HTTP request receives a CSV file as a response. Could this be an issue?
FURTHER INVESTIGATION (05.23.2012):
For some reason when using (in my code) the Yahoo URI http://finance.yahoo.com/d/quotes.csv?s= the response is a 301 (Moved Permanently). When using http://download.finance.yahoo.com/d/quotes.csv?s= instead the response is 200 (OK). Even that both work fine in the browser. I was lucky enough to find this web page that gave me some clues regarding which URIs Yahoo reacts to. Now I can see the "reader" gets the data and everything is ALMOST fine. I still get some strange exception (still trying to figure it out): after reading all the lines in the response I catch a Throwable (I left it from my previous experiments) and later on in the stack I thus get 05-23 08:52:41.258: W/dalvikvm(933): threadid=11: thread exiting with uncaught exception (group=0x40a721f8) and something about an uncaught exception in doInBackground(Void... params). Still investigating...
Just solved this issue - it was just a mistake in calling the Yahoo API. Had to add &e=.csv to the end of the URI for it to work. Just like that: http://download.finance.yahoo.com/d/quotes.csv?s=KDHIX&f=sl1d1t1c1ohgv&e=.csv
FINAL CODE
private ArrayList<String> retrieveStockFinParamsFromYahooApiUri(String yahooApiCall)
{
ArrayList<String> stockFinParamsFromYahooApiUriRows = new ArrayList<String>();
String resultLine = "";
BufferedReader reader = null;
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("yahooGetStockParams");
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(yahooApiCall);
try
{
HttpResponse response = httpClient.execute(httpGet, localContext);
reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
while ((resultLine = reader.readLine()) != null)
{
stockFinParamsFromYahooApiUriRows.add(resultLine);
}
if(response != null)
{
try
{
response.getEntity().consumeContent();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(httpClient != null)
{
httpClient.close();
}
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return stockFinParamsFromYahooApiUriRows;
}
Chances are that you get an Exception in execute that is not an IOException. Then, your catch block never get executed and your finally block is executed before the method throws an exepected exception to the caller of retrieveStockFinParamsFromYahooApiUri.
You have at least 2 options :
don't catch an IOException but a prent class. Try Throwable, print the stack trace and see what happens. Then you can later add other catch blocks to handle the case. (Catching Throwables is a bad programming practice, but you can use temporarily).
place the invocation of retrieveStockFinParamsFromYahooApiUri in a try catch block using the same mechanism as above to determine which exception classes to expect and act accordingly.
But you need to refine your understanding of the problem, catch everything possible, write the stack trace and check the logcat.
Here are some other advices :
You need to check the result code of the request before reading its content.
You could use Apache IOUtils to copy the content of the response input stream and cache it to a file.
You could enable gzipping of the request and the response.
You also need to close properly the HttpConnection in the finally block, you can consume the entity of the response to achieve this.

Android - How to handler timeout

I have a problem with request POST/GET in Android.
I am trying to handle the error:
Caused by: java.net.SocketTimeoutException: Read timed out
To prevent the crash on my application, I added a timeout of 40 seconds. That works but sometimes 40 seconds is not enough to avoid the error.
I tried to add the "try and catch" but it seems that the error isn't occurring inside here:
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
localContext.setAttribute(ClientContext.COOKIE_STORE,
Backend2.cookieStore);
response = HttpManager.execute(request, localContext);
if (response.getEntity() != null) {
final String r = EntityUtils.toString(response.getEntity());
return r;
} else {
return null;
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
return null;
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
I am looking for a solution but when I read on stackoverflow and on google, I see only posts like "increase your timeout, add a try, etc.."
I am doing something wrong?
It's hard to tell just looking at your catch statement, but maybe you are getting a different error than a SocketTimeoutException? Try to catch an Exception instead to confirm that.

Getting "FATAL EXCEPTION : AsyncTask #2". And I don't know what's causing it

While trying to call a web service and get the corresponding json object I get a fatal exception. I have absolutely no idea where to look and what errors to correct.
EDIT:
private class CallServiceTask extends AsyncTask<Object, Void, JSONObject>
{
protected JSONObject doInBackground(Object... params)
{
HttpGet req = (HttpGet) params[0];
String url = (String) params[1];
return executeRequest(req, url);
}
}
And here's executeRequest method called in doInBackground:
private JSONObject executeRequest(HttpGet request, String url)
{
HttpClient client = new DefaultHttpClient();
JSONObject jsonObj = null;
client = getNewHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String response = convertStreamToString(instream);
try {
jsonObj = new JSONObject(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
return jsonObj;
}
Just looking at your LogCat stack trace (in this case) it tells you all you need to know about what this exception is and what has caused it:
thread exiting with uncaught exception
Tells you that an exception has been thrown which your code does not handle
An error occurred while executing doInBackground()
This tells you that your doInBackground() function in your Async task has thrown this unhandled exception
Caused by: java.lang.ClassCastException ...HttpPost... (RestClient.java:275)
And that tells you that you have encountered a ClassCastException, resulting from a HttpPost call at line 275 in that source file.
EDIT:
Should have read that stack trace more carefully... as HandlerExploit has posted It's the HttpPost that's throwing that error, where you're expecting a HttpGet... but the following debug method still stands:
If you add an extra catch (ClassCastException e) with an e.getMessage() you'll most likely see a useful error message that describes the problem in more detail.
When in this situation and I find an unexpected exception being thrown like this I tend to add a temporary 'catch all' (catch (Exception e) { e.printStackTrace() } ) and stick a break point on the e.printStackTrace() so I can see all the details about the exception... might not be the most efficient way of doing it but its a start when you're in the dark!
My best guess would be that :
HttpGet req = (HttpGet) params[0];
Is returning a HttpPost instead of a HttpGet.
Please post where you are calling new CallServiceTask().execute();

Categories

Resources