Android app crashes after setConnectionTimeout - java

I want to implement a setConnectionTimeout in my Android app. I've followed several code structures but couldn't make it work. My app was connected to a localhost server, I just want it to display Connection Timeout if it cannot be connected to the database.
Here is my Http Request code:
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
The problem is when it reaches 3 seconds, the app crashes. Before I implemented this snippet, it just freezes for a longer time. And if I turn off my Wifi, it will return a DialogBox saying that the internet is not connected, and this is what I want to achieve.
Any idea how to return an AlertDialogBox if database couldn't be connected? (I've disabled WAMP for this purpose)

Your exception is saying that there's a null pointer exception while parsing JSON. You didn't attach that code here, so I'm only assuming that once your timeout occurs, you're still trying to parse the input stream into JSON.
It would be good to check if your input stream isn't empty first.

Related

Is a way to set Connection refused time to HTTPGet Apache ?

I want to get a web page but if return Connection refused I want to wait only 1 second
My code :
final DefaultHttpClient client = HTTPSHelper.getClientThatAllowAnyHTTPS(connectionManager);
client.getParams().setParameter(ClientPNames.COOKIE_POLICY,
CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setParameter("http.socket.timeout", 1000);
client.getParams().setParameter("http.connection.timeout", 1000);
client.addRequestInterceptor(new RequestAcceptEncoding());
client.addResponseInterceptor(new ResponseContentEncoding());
final HttpGet get = new HttpGet(url.getUrl());
final HttpResponse resp = this.httpClient.execute(get, localContext);
When returns connection refused I have to wait a lot ...Is there a way to specify time to wait on connection refused ? Thanks
You can set the timeout for the connection this way:
final HttpParams p = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(p, 1000);
client = new DefaultHttpClient(httpParams) ;

Android/PHP/APACHE - POST method doesn't work only with HTTPRequest from Android

I've got a problem. I configured myself a Debian server with an Apache/MySQL/PHPMyAdmin and PHP5. Everything is working very well when I do some test from my browser on my PC.
But this server will be used as a Web Service for my Android Application. And when I try to send my POST HTTPRequest from my Android app, the server doesn't read any POST data.
This is my HTTPRequest code:
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(AbstractServiceKeys.URL);
try {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
for(int index=0; index < params.size(); index++) {
if(params.get(index).getName().equalsIgnoreCase("avatar")) {
entity.addPart(params.get(index).getName(), new FileBody( new File (params.get(index).getValue())) );
} else {
entity.addTextBody(params.get(index).getName(), params.get(index).getValue());
}
}
entity.addTextBody("lang", Locale.getDefault().getLanguage());
httpPost.setEntity(entity.build());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
.....
To see if datas have been correctly sent, I do this on the PHP server side :
print_r($_POST);
print_r($_REQUEST);
It answer me :
Array()
Array()
I know that the problem comes from my server because I tested this on an another server from a friend. But now, I don't know what to do.
Please help mens !
[EDIT] : I found the problem but I can't understand why it didn't work before.
My URL was :
http: //[server_domain_name.com]/index.php
I change it to :
http: //[server_ip]/index.php
And it worked. I don't understand. It's really strange...

Apache HttpClient: set timeout for NoRouteToHostException

I am using Apache HttpClient 4.2.5 and need to set connection timeout for 30 seconds. I do the following:
int timeout = 30 * 1000;
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, timeout);
HttpConnectionParams.setSoTimeout(params, timeout);
HttpClient client = new DefaultHttpClient(params);
HttpGet request = new HttpGet(url.toURI());
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
HttpResponse response = client.execute(request);
But after 12 seconds NoRouteToHostException is thrown form client.execute(request). As I understand, CONNECTION_TIMEOUT and SO_TIMEOUT is useless here. Have you any idea, how to set timeout for NoRouteToHostException? I should hope that server became available within this time. Thanks for any comment and advice!

How to check if web service is available, and then connect to it in one go?

I want to check if a web service is available before connecting to it, so that if it is not available, I can display a dialog that says so. My first attempt is this:
public void isAvailable(){
// first check if there is a WiFi/data connection available... then:
URL url = new URL("URL HERE");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(10000); // Timeout 10 seconds
connection.connect();
// If the web service is available
if (connection.getResponseCode() == 200) {
return true;
}
else return false;
}
And then in a separate class I do
if(...isAvailable()){
HttpPost httpPost = new HttpPost("SAME URL HERE");
StringEntity postEntity = new StringEntity(SOAPRequest, HTTP.UTF_8);
postEntity.setContentType("text/xml");
httpPost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");
httpPost.setEntity(postEntity);
// Get the response
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httpPost);
// Convert HttpResponse to InputStream for parsing
HttpEntity responseEntity = httpResponse.getEntity();
InputStream soapResponse = responseEntity.getContent();
// Parse the result and do stuff with the data...
}
However I'm connecting to the same URL twice, and this is inefficient and probably slowing down my code.
First of all, is it?
Secondly, what's a better way to do this?
I would just try connecting, if it times out, handle the exception, and display an error.
May be you should consider looking at HttpConnectionParams class methods.
public static void setConnectionTimeout (HttpParams params, int
timeout)
Sets the timeout until a connection is etablished. A value of zero
means the timeout is not used. The default value is zero.
public static void setSoTimeout (HttpParams params, int timeout)
Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is
the timeout for waiting for data. A timeout value of zero is
interpreted as an infinite timeout. This value is used when no socket
timeout is set in the method parameters.
Hope this helps.
As above and here is how you check for times out:
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
And then pass the HttpParameters to a constructor of httpClient:
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

REST PUT Response format

I have an android application with a MySQL database. Rows entered on the android tablet need to be synchronised on a server, also with MySql. Once written onto the server the server Unique Integer needs to be returned to the tablet to update the local database. That way it will x-ref the client to the server. It currently works by performing a PUT for each row and using the location for the server ID in the response. However it takes ages if there are a significant amount of updates, inserts as each one row opens a new HttpConnection. I would like to be able to group the updates in one XML String and get an XML file returned with the xreference of the serverID for each Client ID. However I cannot find a way of sending XML in the response, only a URI. My connection code is
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, Const.HTTP_CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, Const.HTTP_SOCKET_TIMEOUT);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
client.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("xxxxx","xxxxx")); // TODO Change to logged user name
HttpPut put = new HttpPut(uri);
StringEntity entity = new StringEntity(xml);
entity.setContentType("application/xml");
put.setEntity(entity);
HttpClientParams.setRedirecting(put.getParams(), false);
HttpResponse response = client.execute(put);
switch (response.getStatusLine().getStatusCode()){
case 200:
case 201:
location = response.getLastHeader("Location").getValue();
key = location.substring(location.lastIndexOf("/")+1);
break;
case 401:
throw new RuntimeException("Authorisation Failed");
default:
throw new RuntimeException("Failed to Create Data Record on Server");
}
And on the Server
if (flight.getClientFlightId()!=0){
if (insertFlight(userId)){
xref += "<clientId>"+flight.getClientFlightId()+"</clientId><serverId>"+flight.getServerFlightId()+"</serverId>";
}
}
xref +="</xref>";
response = Response.created(URI.create(xref)).build();
Anyone able to help please?
ArrayList<NameValuePair> putParams = new ArrayList<NameValuePair>();
putParams.add(new BasicNameValuePair("myXML", "<xml> _PUT_YOUR_XML_HERE_ </xml>"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(putParams);
put.setEntity(formEntity);

Categories

Resources