Android server http Connection - android

My android app is connected to my server thorugh http connection.The server will close the connection after 10seconds . But in client side(android) i want to close the connection in 5 seconds neither i receive data or not from the server my android app must close the connection.
when I tried setsotimeout(5000) two things happens
1.The android app is sending request again and again for every 5000milliseconds.
2.It works well in the case when the server closes.
Suggest me some good logic
protected String doInBackground(Object[] params)
{
try
{
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("carddata", "this " + "is " + "normal" + "transaction"));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/MyServletProject/DoubleMeServlet");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
httpPost.setParams(httpParameters);
HttpResponse response = httpClient.execute(httpPost);
Log.d("Http Post Response:", response.toString());
HttpEntity entity = response.getEntity();
dsds = EntityUtils.toString(entity);
} catch (Exception e)
{
if (e.toString().equals("java.net.SocketTimeoutException"))
{
dsds=e.toString();
}

If I was you, I would create a layer between by http client and my app. Every time a request is made, it restarts a 5000ms timer to kill the connection.

Related

Why my Httppost is not working when I turn off the screen?

I have one application in Android and I have two threads. One thread is checking the coordinates every 10 seconds and the other thread is sending this coordinates to my Server with Httppost.
When the screen is turn on the application works also when the application is in background.
But, when I turn off the screen the thread that checks the coordinates works but the thread that sends the Httppost does not work until I turn on the screen. Why?
#Override
public void run() {
try {
HttpPost httppost = new HttpPost("MY_URL");
HttpClient httpclient = new DefaultHttpClient();
jsonArray = getJSONArray();
nameValuePairs.add(new BasicNameValuePair("msg", String.valueOf(jsonArray)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpresponse = httpclient.execute(httppost);
Thread.sleep(myService.getIntervalCoordinates() * 1000);
} catch (Exception e) {
}

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.

android why sending information to server works with WIFI only?

I am sending information to a server via WIFI and everything works great.Now i want to send information to a server with mobile data too, and i do not know why only works with WIFI, with mobile data trows an exception of failed to connect to server.
this is the part that fail with mobile data; with WIFI works perfectly:
int length=values.length();
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,9000);
HttpConnectionParams.setSoTimeout(httpParams, 9000);
HttpClient client = new DefaultHttpClient(httpParams);
String url = saveData+"?Length="+length+"&Table="+temp;
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(values.toString().getBytes("UTF8")));
request.setHeader("json", values.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
Log.d("test 7","test 7 last");
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.d("here",""+result);
if(result.equals("success")&& ReadyOff==false){
Ready=true;
}else{
Ready=false;
ReadyOff=true;
}
Log.d("sent","valor de ready"+Ready);
}
so i am doing something wrong?
`
You cannot contact your server from the device's mobile network unless it is routable from the public Internet.
A server running on your development machine or otherwise behind a NAT/firewall would typically only be accessible from your local network / wifi.

Android httppost network violation

I have a problem with my android app. I mean I'm using the code from one of tuts in the internet, looks like below
public static String sendLocation(String s) {
// Create a new HttpClient and Post Header
//HttpParams params = new BasicHttpParams();
//params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://google.com/read.php");
//String d = "ok";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", "mobile"));
nameValuePairs.add(new BasicNameValuePair("location", s));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// d = "CPE";
} catch (IOException e) {
// d = "E";
}
return "send";
}
}`
And the problem/bug appeared when the app try to send data to the remote server (the line below)
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
I also use the StrictMode and after that everything works, the logs shows network violation
11-08 22:34:40.020: D/StrictMode(939): StrictMode policy violation; ~duration=359 ms: android.os.StrictMode$StrictModeNetworkViolation: policy=31 violation=4
I included in the manifest file appropriate permission
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
Do you have any idea what should I do to run my app (actually send data via post to the server) without StrictMode?
The problem is that you are trying to do network calls on the main UI thread. Only use those types of methods in a separate thread.
A good example of that is here.

Android development -Unknown Host exception problem

I'm developing an Android app that gets a JSON_encoded result from a php middleware script that connects to a MySQL database. I have given the application Internet permissions.
The problem I'm having is that the program gives an UnknownHostException error the first time it is run. I have the program on a timer, and subsequent calls to the timer handler function do not return the UnknownHostException error. Do you have any idea why this would occur? I have tested the domain and made sure that it connects correctly through a web browser.
Here's a snippet from the code:
public final void timerAlert(){
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run() {
Timer_Method();
handler.postDelayed(this,1000);
}
};
handler.postDelayed(r, 1000);
}
public void Timer_Method()
{
//See if this buzzer is being signaled.
String result = null;
InputStream is = null;
StringBuilder sb=null;
//http post
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("BuzzerID",BuzzerID.toString()));
Toast.makeText(getBaseContext(), "BuzzerID="+BuzzerID.toString() ,Toast.LENGTH_LONG).show();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://domain/getBuzzStatus.php?BuzzerID="+BuzzerID.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
Toast.makeText(getBaseContext(), "Hm, problem here="+e.toString() ,Toast.LENGTH_LONG).show();
}
Note that domain has something else there in the actual code and that this is just a snippet but is where the first issue occurs. Also note that I am mixing get and post, something I'd rather not do, but for some reason passing the nameValuePair to the php script doesn't send anything to $_REQUEST.
A snippet from the very simple PHP script:
$sql_string="SELECT Signal FROM BuzzCustomer WHERE idBuzzCustomer=" . $_GET['BuzzerID'];
$sql = mysql_query($sql_string);
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
I switched to $_GET here because I could not get $_REQUEST to work. Any help would be appreciated. Thanks in advance!
May be their will be no Internet connection in the simulator......Check a url in browser
Instead of
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Use
ResponseHandler<String> response = new BasicResponseHandler();
String result = httpclient.execute(httppost,response);
Also put Internet permission in the Manifest
Just a guess, but maybe the DNS request takes too long and your HttpClient gives up, but the request is finished and cached so the next time it does not fail?
This With Apache HttpClient, why isn't my connection timeout working? seems to be a question about how to set the timeout for HttpClient.

Categories

Resources