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?
Related
Have a problem with implementing GCM.
Server side i used the HTTP method. Created the war file and uploaded it to apache tomcat (only changed the API in "samples/gcm-demo-server/WebContent/WEB-INF/classes/api.key" with the server api from the dev console). When i access the page i get a "No devices registered!".
Implemented the Android part as well, hit the register button, got a response from GCM with the registeredId, thus, i presume that the device got registerd in teh GCM. The problem comes when i go back to my webpage and I see the same message: "No devices registered".
Tried to look for similar errors, but only found old GCM api implementations.
Have any idea for a way to figure out if the problem comes from my server, the gcm server or it's something bad with the android part itself?
I guess you should fill SERVER_URL in gcm-demo-client/src/com/google/android/gcm/demo/app/CommonUtilities.java
and check whatever the HTTP call to the servlet http://Your-IP/register is really executed after the GCM registration to Google in order to let the gcm-demo-server, that you are using, to run correctly and send the push notification to that Registration ID.
Don't forget to keep the server running because it saves RegIDs in memory through the Datastore class
try this:
private void sendRegistrationIdToBackend() throws Exception {
// Your implementation here.
String URL="http://Your_Server_IP/gcm-demo/register?regId="+SENDER_ID;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}
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.
I am trying to connect to my database on my localhost through my android application. I have created a php file and stored it in my wamp/www/myfolder, when I run it it works fine, so it must be a problem with my android class.
public void getData(){
String result ="";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/testdata/getAllCustomers.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection");
resultView.setText("Couldnt connect to database");
I have gone over my code many times but I can't find the problem.
I have created two morw try catches in this method that convert the result and the other one parses the data but when I run it the first log appears so it doesn't connect to the database.
P.s I am using eclipse, to I need a plugin for json, I know eclipse IDE supports it.
NetworkOnMainThreadException means that you are attempting to perform a network operation on the main thread, which is forbidden. Simply do it from another thread. This is mainly done by creating an AsyncTask. Here's an example. And here's another one.
It's worth noting that NetworkOnMainThreadException is only thrown for applications targeting the Honeycomb SDK or higher, but the behaviour is always heavily discouraged.
The loopback address in case of android when you are trying to connect from emulator is 10.0.2.2
i.e instead of localhost use 10.0.2.2
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
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