android why sending information to server works with WIFI only? - android

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.

Related

Android server http Connection

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.

Sending JSON From Android to PHP

I've been struggling a bit on sending JSON objects from an application on android to a php file (hosted locally). The php bit is irrelevant to my issue as wireshark isn't recording any activity from my application (emulation in eclipse/ADK) and it's almost certainly to do with my method of sending:
try {
JSONObject json = new JSONObject();
json.put("id", "5");
json.put("time", "3:00");
json.put("date", "03.04.12");
HttpParams httpParams = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://localhost/datarecieve.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
I've modified this from an example I found, so I'm sure I've taken some perfectly good code and mangled it. I understand the requirement for multi-threading so my application doesn't hang and die, but am unsure about the implementation of it. Would using Asynctask fix this issue, or have I missed something else important?
Thankyou for any help you can provide.
Assuming that you are using emulator to test the code, localhost refers to the emulated environment. If you need to access the php hosted on your computer, you need to use the IP 10.0.2.2 or the LAN IP such as 192.168.1.3. Check Referring to localhost from the emulated environment
You can refer to Keeping Your App Responsive to learn about running your long running operations in an AsyncTask
you should use asynctask or thread, because in higher versions of android it doesn't allow long running task like network operations from ui thread.
here is the link for more description

Android HttpPost data

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.

android server post data

I am new to android networking and would like to find the best solution/source that would help me learn the same. I have a working android application but i want to include network services that can get and send data to the webserver. While i was searching for the same i found link ( http://www.helloandroid.com/tutorials/connecting-mysql-database ) which dont produce any results. I also found that SOAP or REST (with android) are probably recommended methods, if so please give complete tutorials to learn the same ( i have no prior knowledge on webservices). In my application I would be required to send data to the server and receive data from the servers sql
Thank you
This is for post data on server,
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// get response entity
HttpEntity entity = response.getEntity();
// convert entity response to string
if (entity != null)
{
InputStream is = entity.getContent();
// convert stream to string
result = convertStreamToString(is);
result = result.replace("\n", "");
}
or see how to post data to remote server in android app [closed], Post the data to Server

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