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.
Related
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.
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.
I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.
I am trying to send data to my server using HttpPost via the following code.
private boolean FacebookLogin(String url) {
boolean isDataSend = false;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data", FacebookData()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse res = client.execute(request);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String bufstring = EntityUtils.toString(res.getEntity(),
"UTF-8");
isDataSend = true;
}
} catch (Exception e) {
}
return isDataSend;
}
Is there any way i can have a look at how the $_POST looks on the server end. so that it will be easier for me to code the server part.
You can write the received $_POST on a file. Sometimes I do that. It's not the most elegant solution, but it works fine.
Try using a http proxy (e.g. Fiddler) for debugging, it helps a lot in these cases. You can set up an emulator to use this proxy for network communications, so you can inspect the messages sent and received. Check out the emulator docs on how to configure it to use a proxy.
I'm trying to cancel my AsyncTask when connecting to the server fails. I tried cancel(), but the onPostExecute() method still gets called, instead of onCancelled().
This is what I have inside doInBackground():
protected String doInBackground(String... params) {
Log.i("ping", "doInBackground() started");
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpResponse response;
HttpEntity entity;
try {
HttpPost post = new HttpPost("http://192.168.1.6/ping/login.php");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", getEmail()));
nvps.add(new BasicNameValuePair("password", getPassword()));
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = client.execute(post);
entity = response.getEntity();
InputStream iStream = entity.getContent();
read(iStream);
iStream.close();
if(entity != null)
entity.consumeContent();
Log.i("ping", "doInBackground() vervolgd");
} catch (Exception e) {
e.printStackTrace();
Log.e("tvsping", "Exception: " + e.getMessage());
cancel(true);
}
return null;
}
I'm trying to see what happens when the server can't be reached (I'm shutting it down, so there's no way my phone is getting any response) and I get IOException: the connection was reset.
Any ideas how I should check if the connection isn't made?
update
I solved this like Tanmay suggested, with a boolean. But I have another problem:
Every time doInBackground() is called it takes about three minutes to stop, when it can't find the servers. Everything is fine when it can reach the server, but I can't have this taking 3 minutes before the user is notified of anything (I could do a background process, but still a 3 minute wating bar is no good neither)
Any ideas what is wrong with my code? This can't be normal, right?
From doInBackground() method you are returning a String .You can return null if your HTTPPost fails.And then in onPostExecute() method just check what are you getting, if the String is null dont do anything which you really want and on successful running do your UI work
Hope this will help you.
HttpHost target = new HttpHost("192.168.2.3", 80);
HttpPost post = new HttpPost("/ping/login.php");
response = client.execute(target, post);
This solved the slow server response for me.