Genymotion unable to connect to server? - android

I have an app that sends a http request to a server and receives a JSON for processing. I test it on both a physical device and Genymotion.
The app runs fine on the physical device but on Genymotion throws NetworkOnMainThreadException.
I tracked the exception and this is the part with the issue:
..
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
// Exception on this line:
HttpResponse httpResponse = httpClient.execute(httpPost);
//
HttpEntity httpEntity = httpResponse.getEntity();
...
It seems that the Genymotion can't connect to server to execute the request. But its browser loads the sites just fine.
So, anyone knows what's going wrong here?

I found what the problem was:
As explained in this answer, since API 11, the NetworkOnMainThreadException is thrown to inform using long-running tasks (like http communications) in the main thread.
By using AsyncTask the problem was resolved and everything worked as it should.

Related

What exactly these lines do individually and collectively in JSON parsing

I am wondering after I searched in few books and on web that none of then detailed about it. I want to know that what exactly the purpose of below line individually while we parse JSON response file :
Lines ARE :
DefaultHttpClient client=new DefaultHttpClient();
HttpPost post = new HttpPost(Url);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
I know one thing that all together these four lines perform the connection with the server, but have no idea what individually the do.
I am sure I will get answer here from one of SOF besties.
Android's DefaultHttpClient Supports:
HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.
HttpPost :
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.
HttpResponse :
Takes care of the response that is got after executing client.execute(post);
Finally the following code obtains the message entity of this response.
response.getEntity()
Please check the android documentation for detailed implementation.
Code above is resposible for Http post request to server and get JSON response, so that you can parse and get required data.
Above 4 lines don't do JSON parsing. They only make an HTTP connection and the way of doing it is only recommended below Gingerbread. For Gingerbread and above use HttpURLConnection. More details here.
After you have the content (make a check if the response code is as expected - 200 or 201) you can proceed to JSON parsing. Use either Jackson, GSON or Android's json framework (this is my preferred order).
As per may Opinion
DefaultHttpClient client=new DefaultHttpClient(); responsible for HttpsURLConnection efficient(Connection) when connecting to up-to-date servers, without breaking compatibility with older ones.
HttpPost post = new HttpPost(Url); responsible for get POST request and send response.
HttpResponse response = client.execute(post); responsible for executes HTTP request using the default context.
HttpEntity entity = response.getEntity(); responsible for carry a content entity associated with the request or response.
For more information go to:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

Android: HttpClient remote vs. local server

I'm having problems with an app that works when connecting to a remote web server, running a php script against a database. However, when I point the same app to my local web server running on my machine, things doesn't work.
Here's the code I use for connecting to the remote web server (it needs authentication):
(All the networking code is done inside an AsyncTask class.)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
StringBuilder authentication = new
StringBuilder().append("frankh").append(":").append("vriceI29");
result = Base64.encodeBytes(authentication.toString().getBytes());
httppost.setHeader("Authorization", "Basic " + result);
nameValuePairs.add(new BasicNameValuePair("date", date));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
For the connection to the local server, which doesn't use authentication, I'm commenting out these lines:
//StringBuilder authentication = new
// StringBuilder().append("frankh").append(":").append("vriceI29");
//result = Base64.encodeBytes(authentication.toString().getBytes());
//httppost.setHeader("Authorization", "Basic " + result);
However, I get two different errors, depending on how I phrase the url to the local web server.
If I use this url: "http://localhost.shoppinglistapp/fetchlist.php"
I get this error:
Error in http connectionjava.net.UnknownHostException: localhost.shoppinglistapp
If I skip the http part in the url, I get this error:
Error in http connectionjava.lang.IllegalStateException: Target host must not be null,
or set in parameters.
What am I doing wrong here? The remote server is a Linux Apache server, and the local server is IIS 7. The local server is supposed to be just for working on when I've got no or a bad internet connection, so it's not critical, but I hate not knowing why things doesn't work.
If you testing via your local emulator, you'll want to use 10.0.2.2 instead of 'localhost'.
Referring to localhost from the emulated environment

sporadic timeouts on http connection

In my application I use http to connect to my server (I am synchronizing the local database). Here is the code:
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),13500);
HttpConnectionParams.setSoTimeout(httpClient.getParams(),27000);
HttpResponse response = httpClient.execute(httpRequest);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
String data = EntityUtils.toString(entity);
JSONObject jObj = new JSONObject(data);
entity.consumeContent();
}
This code is executed for a number of httpRequests to pull the data from the server as well as to send updates up to the server.
Till recently this code did not give me any trouble, but now I am struggling with a strange problem: Sometime the code works as it is supposed to work, but sometimes all I am getting is timeouts.
A little more details - when it does not work it is not like I am getting sporadic timeouts - every request I send ends up with a timeout. I can restart the app and see this behavior, and then after several app restarts it is like the curse is lifted - not a single timeout. And then again all I am getting is timeouts.
I am pretty sure that the problem is on the phone side, because I also have an IPhone app talking to the same app with no problems. Also several times I observed this problem with one android device, while the same app on a different device working fine.
What am I missing here?

Android & T-Mobile Internet Connection Problem

So, this is a strange one. I have an app that uses permission INTERNET but am unable to access the Internet on any T-Mobile device. If the device is on wifi, the app works as intended. The app also has been tested with AT&T and Sprint devices and works as intended with or without a wifi connection.
Following, is a sample of code I use to connect with Google. The response returns as 200 and OK but the app throws an Exception on the last included line, as the content length is -1. All other Internet apps on the phone work as intended, i.e. are able to connect to the Internet. I tried throwing every available standard permission in my app and have had no luck. Anyone seen this before or have any idea? Thanks.
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpResponse response = httpClient.execute(httpGet, localContext);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity qrEntity = response.getEntity();
byte [] buffer = new byte[(int) qrEntity.getContentLength()];
It seems T-Mobile is blocking my API.
http://www.developer.nokia.com/Community/Wiki/T-Mobile_U.S._API_access_rights

problem in connecting to my EC2 instance from android simulator

i am facing strange problem i deployed a webservice in EC2 which is up and working fine, but when i am trying to do a REST request on these service I am getting java.net.SocketException: The operation timed out. When i am trying the same URL in my laptop browser it is working but when i am trying this in Android emulator browser it is giving me error.
here is my code
REST URL: http://122.248.194.88:8080/data_for?train=12657
code:-
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://122.248.194.88:8080/data_for?train=12658");
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
`
this httpclient.execute is returning the socket exception is there anything more which i need to know??
I am behind a proxy though but i set that proxy in eumulator options while starting the emulator.
I used the example here: http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html to consume a JSON string. It works perfectly.

Categories

Resources