Strange HttpResponse in Android - android

I am having an unusual problem regarding the following code in an android application.
public InputStream retrieveStream(String url) {
HttpGet request = new HttpGet(url);
HttpParams httpParams = new BasicHttpParams();
int some_reasonable_timeout = (int) (10 * DateUtils.SECOND_IN_MILLIS);
HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);
HttpClient client = new DefaultHttpClient(httpParams);
try
{
HttpResponse response = client.execute(request);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK){
HttpEntity getResponseEntity = response.getEntity();
return getResponseEntity.getContent();
}
else
{
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
}
catch (ClientProtocolException e)
{
Log.e("Methods", "HTTP Error", e);
return null;
}
catch (IOException e)
{
Log.e("Methods", "Connection Error", e);
return null;
}
}
Within the application I attempt to connect to a localhost.(In an AsyncTask)
InputStream source = retrieveStream("http://10.0.2.2:27080/testdb/_hello")
When running on the emulator, this code works fine and if the localhost is down, "source" is returned as null as expected. Similarly when running the code on a mobile device (HTC Nexus One, Android Version 2.2), the code reports "source" as null as expected.
However when running the same APK on another mobile device (Samsung Galaxy S2, Android Version 4.0.3, samsung release), the status code returned is given as HttpStatus.SC_OK, even though it couldnt possibly be connecting to the localhost. Has anyone encountered a similar problem?

Android > 3.0 does not allow to execute web request on Main UI Thread. you need to use AsyncTask to make web request. IN android > 3.0

Related

Android HTTPClient sometimes slow connecting?

I seem to be having issues with the Android HTTPClient some times its super fast and other times it can take a good few seconds to return a result or says connection refused.
As a test I have tried different web hosts and direct IP also with no effect, testing is on a device connected via wifi.
The code is also running on a thread so not on the main thread.
The code i am using is as follows:
String strURL = "http://www.example.com/webservice/index.php";
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(2);
nameValuePairList.add(new BasicNameValuePair("command", "saveFave"));
nameValuePairList.add(new BasicNameValuePair("rid", strID));
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
params.setParameter(CoreProtocolPNames.USER_AGENT, "AppName_Android");
DefaultHttpClient hc = new DefaultHttpClient(params);
HttpPost post = new HttpPost(strURL);
try {
post.setEntity(new UrlEncodedFormEntity(nameValuePairList));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
hc.setRedirectHandler(null);
HttpResponse rp = hc.execute(post);
Log.d("Http Post Response:", rp.toString());
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
jsonData = EntityUtils.toString(rp.getEntity(), HTTP.UTF_8);
Log.v(TAG, "JSON Response " + jsonData );
} catch (Exception e) {
Log.v(TAG, "error " + e.getMessage());
}
you should be able to tweek the timeouts in debug to throw errors so you can get more data on the cause...
this.config = RequestConfig.custom()
.setConnectTimeout(6 * 1000)
.setConnectionRequestTimeout(30 * 1000)
.setSocketTimeout(30 * 1000)
.build();
That is normal behaviour on networks. I see it every day. Sometimes the first connection is fast but mostly slow. The next request goes often faster but not always. It can go slower too. For speed there is no guarantee.

My HttpGet call to retieve my stream, sometimes stops and doesn't continue, even after timeout

I use to make two types of httpGet call. One for parsing JSON with Gson and one for getting the string, for small JSONs....
This is what I use for parsing with GSON:
static HttpGet getRequest;
static HttpResponse getResponse;
#SuppressLint("NewApi")
public static InputStream retrieveStream(String url) {
if (android.os.Build.VERSION.SDK_INT >= 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
int timeout = 30000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
HttpConnectionParams.setSoTimeout(httpParameters, timeout);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
getRequest = new HttpGet(url);
try {
getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ERROR", "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
} catch (IOException e) {
getRequest.abort();
Log.w("ERROR", "Error for URL " + url, e);
} catch (Exception e) {
getRequest.abort();
Log.w("ERROR", "Error for URL " + url, e);
}
return null;
}
Yes, almost always, if there are some errors on JSON or there's no connection, it gives me null and I handle it.
Yes, almost always, if JSON is correct and I have connection, I can parse it successfully.
But few times, I think around 10 or 11 in one month, it doesn't do anything. It stops and doesn't continue (I let it for 20 minutes). It doesn't return null due to URL error, JSON error or TIMEOUT, it just stops. In that moment, my connection is stopped (no movements) but my connection works normally (because I receive messages from, for example WhatsApp).
So, if I open a ProgressDialog, it never closes because I can't handle a null or a successful InputStream, so I can't make the user know that, in the worst of the cases, he/she has to retry.
I'm making all this stuff asynchronously.
What am I doing bad?
Thanks in advance.

UnknownHostException in version 4.1.2 in Android

I have an HTTP get Service url and i can connect and get resource from this url on almost all version of sdk but in 4.1.2 it gives UnknownHostException. Internet permission is already there and also internet connection is active. Please help.
Here is code:
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("myhosturl");
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null)
{
String response = EntityUtils.toString(resEntityGet);
}
}
catch (Exception e)
{
e.printStackTrace();
}
Actually this url is called when there is any incoming call that time it gives exception. If i hit this url any other time it works.

Test in emulator is ok, but it can not on phone

I test in emulator it can run correctly. But I test on the phone, it always throw an exception.
public static String doGet(String url) {
try {
HttpGet method = new HttpGet(url);
DefaultHttpClient client = new DefaultHttpClient();
// HttpHost proxy = new HttpHost("10.0.0.172", 80); The two sentence added on the phone, it still can not run
// client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
method.setHeader("Connection", "Keep-Alive");
HttpResponse response = client.execute(method);
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK)
throw new Exception("");
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
return "Connection errors!";
}
}
I check API4 when create project. And test in emulator android 1.6. Test the phone is on android 2.3.3. I also test in computer android-x86 2.2 jars. It is no problem. I add <uses-permission android:name="android.permission.INTERNET"/> in AndroidManifest.xml. I do not know the reason. Anyone’s opinion is thankful.
What thread you call this function? You cant create connection in UI thread

Android application doesn't trust certificate

I have a certificate to secure my site, certified by: Thawte DV SSL CA, Thawte, Inc.
Now I made an android application that connects to a webservice from this site.
It used to work fine when just going for http://www.myserver.com.
But now that it's secured, and going for https://www.myserver.com I'm having some issues.
I use 2 phones to test my application.
HTC Desire S with Android 2.3.3 (has SD card)
Huawei Ideos X5 with Android 2.2.1 (no SD card)
The HTC does not have any problem connecting to the https.
The Huawei however gives a "Not trusted certificate exception".
The code I used to try and connect is the following:
public String performRequest(String message, String url, Context context) throws IOException {
AndroidHttpClient hc = AndroidHttpClient.newInstance("Android",context);
Log.d(MobileConnectorApplication.APPLICATION_TAG, "NETWORK - Message to send: "+ message);
HttpPost p = new HttpPost(url);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParams, threeMinutes );
p.setParams(httpParams);
try{
if (message != null)
p.setEntity(new StringEntity(message, "UTF8"));
}catch(Exception e){
e.printStackTrace();
}
p.setHeader("Content-type", "application/json");
String response = "";
HttpContext httpcontext = new BasicHttpContext();
httpcontext.setAttribute(ClientContext.COOKIE_STORE, MobileConnectorApplication.COOKIE_STORE);
try{
HttpResponse resp = hc.execute(p,httpcontext);
InputStream is = resp.getEntity().getContent();
response = convertStreamToString(is);
int httpResponsecode = resp.getStatusLine().getStatusCode() ;
checkResponse(url, message, response, httpResponsecode);
Log.d(MobileConnectorApplication.APPLICATION_TAG, String.format("NETWORK - Response %s : %s", httpResponsecode, response.length() > 150 ? response.subSequence(0, 150): response));
} finally{
hc.close();
}
return response;
}
This part of the code was made by someone else a few months ago and he isn't around to change it and my knowledge about these connections isn't so great.
could someone help me out? Thanks in advance!

Categories

Resources