Send data from android to php - java

I need to help about to send data from android to php. I have this java code for android;
public void sendToDb()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pLat",Double.toString(lat)));
nameValuePairs.add(new BasicNameValuePair("pLng",Double.toString(lng)));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://123456.com/welcome.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
and I have in my php folder this codes;
<?php
$pLat = $_POST['pLat'];
$pLng = $_POST['pLng'];
$result = mysql_query("update Users set lat='$pLat',lon='$pLng' where username='ozi');
if (mysql_affected_rows()==0)
{
$query = "INSERT INTO Users ";
$query .= "(lat,lon) VALUES ('$pLat','$pLng')";
}
}
?>
When I send to data from my phone there is no problem but after I look mysql lat and lot rows not null but empty.
Is there a problem that you see in codes?

After reading your comments, what you're trying to do (I think) is persist data. The php file does nothing but run the code you have. The POST variables are only alive if you pass them in the request. The request is coming from the Android app along with POST variables and the response to the Android app will have the correct output.
The request coming from your browser is a "GET" and does not send a pLat or pLng variable, so there is no variables to output.
This is a very basic concept of HTTP that you must grasp.
What you are trying to do is save the data somewhere. PHP can do that by saving it to a database (such as MySQL) or by simply outputting the POST variables to a local file. A quick google search can show you how to save files and open databases. Heck, you can even just send them in an email to yourself.
The PHP script will only hold those variables for the life of the script and then release them out of memory forever. It's up to you to use the power of PHP to save those variables somewhere else.

At a glance I can already see some insanity here. Why do you specify where username= { $_SESSION['username']} when the call is coming from an android device? What session is there? Additionally, if this fails you insert with no username. but then never run the query.
if (mysql_affected_rows()==0)
{
$query = "INSERT INTO Users ";
$query .= "(username, lat,lon) VALUES ('ozi', '$pLat','$pLng')";
mysql_query($query) or die(mysql_error()); // <---- this would need to be run
}
}
I suggest you fix those 2 very critical observations first, then update your question with a more targeted problem. Then I may update this answer to be more useful.

Related

Box API Updating Email Alias Issue

I am trying to update email alias for different users. I am able to authenticate, get the code and then get the access token. I am sending the access token in the HTTP POST request as a Header. I am using Java & Apache HTTPClient to make the RESTful call. Here is the code snippet (Only relevant code shown).
if (httpClient != null) {
String apiURL = getApiURL();
apiURL = MessageFormat.format(apiURL, "firstname.lastname#company.com");
// apiURL = https://api.box.com/2.0/users/firstname.lastname#company.com/email_aliases
// firstname.lastname#company.com does exist in the Box Account
HttpPost post = new HttpPost(apiURL);
post.addHeader("Authorization", "Bearer "+accessToken);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", "updateemail#company.com"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Charset.defaultCharset()));
HttpEntity entity = post.getEntity();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseFromBox = httpClient.execute(post, responseHandler);
writeResponse(response, responseFromBox);
if (responseFromBox != null) {
if (logger.isDebugEnabled()) {
logger.debug("apiURL-->"+apiURL);
logger.debug(responseFromBox);
}
}
}
The problem is that the response I get is some HTML code that says "The page you were viewing has expired. Please go back and try your request again." I was expecting some JSON string.
What I am doing incorrect? In the Post request instead of sending the email address I used the user id. But I get the same error.
In fact when I try to fetch the email alias of a user using the HTTP GET request I get an error "Not Found". The user does exist. I have an admin control. I can see them.
Thanks
Raj
Try a get on /users to get the array of all your users in the enterprise first. Is that working for you? If not, can you do a get on /users/me? If you can't get the former, then your API key may not have the "manage an enterprise" grant setup for it. You have to set that up in the app management, where you setup your OAuth2 callback URL.
Not sure why you are getting HTML back. That usually only happens on badly formed requests that our servers can't even parse, like you are hitting the wrong URL.
Just a reminder, OAuth2 URL is different from the API URL. 1st is https://www.box.com/api/oauth2/.... 2nd is https://api.box.com/2.0/...
As for setting the Email alias, that's entirely possible, once you know the ID of the user you are trying to set the alias for. Documentation is here
I was using the NameValuePair instead of the JSON string that was being expected. So I removed the following
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", "updateemail#company.com"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Charset.defaultCharset()));
and added
String json = "{\"email\":\"firstname.lastname#company.com\"}";
StringEntity entity = new StringEntity(json, Charset.defaultCharset());
post.setEntity(entity);
and then things started to work!

new to java - understanding an HTTP POST request

I have been trying to understand the postData() method in the following tutorial.
My understanding of the code is:
an nameValuePairs object, which contains some data is being sent over the internet to some web service located at this address: http://www.yoursite.com/script.php which will receive this nameValuePairs object
For example you want to send the age of a person to the webservice.
If you send data via GET the call of the webservice would be like this:
http://www.yoursite.com/script.php?age=18
If you send data via POST the call of the webservice would be like this:
http://www.yoursite.com/script.php
and the key-value arguments are integrated in the data stream of the request
So, to answer your question, no object will be sent,
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("age", "18"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
will integrate the key-value-list to the data stream of the request.
Yes, basically... server gets that name-value pair and can process it as it wants ...
For example when logging into your email account, you are sending two name-value pairs - username=your_username and password=your_password ... after receiving, server checks if username you sent is correct and if the password is valid for given username, and then sends you to your account or throws a message that data you supplied is invalid.
It is not java specific. It is http protocol, that can be implemented in any other language.
If you pass an id in like this,
nameValuePairs.add(new BasicNameValuePair("id", "20"));
In php page, you can get the value like this,
$id= $_POST['id'];

Large data is not sending in android through webservice

I am using the following code in android to send data to a server through a web service
call.When i am sending small amount of data it is hitting the server.When i am sending large data it is not hitting the server.Simply it is httpClient.execute(httpPost); .But i am not getting any result.What might be the problem
HttpPost httpPost = new HttpPost(url+data);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
if (rsopnse != null)
System.out.println(httpPost.getMethod());
try
{
httpResponse= httpClient.execute(httpPost);
}catch(Exception e)
{
e.printStackTrace();
}
Thanks in advance...
You need to create a List<NameValuePair> for all the parameters that you want to pass in the Request. You should not append your parameters to the URL, which is more of the GET style of making a call.
The examples for HTTP Post are covered in the post here.

Java httpPost not posting data correctly (Apache library)?

Quick question as I've tried many debugging options and none have helped identify the problem. I'm using Java and the Apache HttpPost library.
I have httpGet and httpHead working fine currently, however I can't get httpPost to send the variables correctly. I set up a debug PHP script on my server to simply dump the contents of $_POST. Works correct if I do a curl request in terminal.
Code snippet:
// create new HttpPost object
postRequest = new HttpPost(url);
// add post variables
postRequest.setEntity(new StringEntity(body, ContentType.TEXT_HTML));
// execute request
response = executeRequest(postRequest);
The String variable "body" is just a string, currently containing "test=testing". The output from this PHP debug script:
<?php
echo "Input Stream: ";
var_dump(file_get_contents('php://input'));
echo "POST Variables: ";
var_dump($_POST);
?>
is :
Input Stream: string(12) "test=testing"
POST Variables: array(0) {
}
Does anyone know why it's not getting picked up and dumped in the $_POST variable? Highly irritating as I've spent hours on this!
Any help would be appreciated :) thanks
See Access all entries of HttpParams
To build the URI including the parameters, use:
NameValuePair nvp = new BasicNameValuePair("test", "testing");
String query = URLEncodedUtils.format(nvp, "utf-8"); // use your favourite charset here
URI uri = new URI("http://localhost/app?" + query;
HttpPost postReq = new HttpPost(uri);
httpClient.execute(postReq);
This will result in: http://localhost/app?test=testing being requested.

Get data from PHP script in JAVA

I am fairly new to Android programming and was wondering how I can get data from an SQL database in my Android app.
I currently have a PHP script that pulls the data I want from the SQL table but I'm not sure how to pull the data from the PHP script into my Java. How do I do this? I read something about SOAP. Is this the protocol I want to use?
Thanks
It depends. Where's the database, on the device, or on a server? If it's on the server, is the PHP code already a web app, or is it just a script?
In general, if the database is on the device, throw out the PHP and use JDBC to grab the data directly from Java. If the data is on the server, then turn the PHP script into a web app, and access that web app from Java. SOAP is certainly one protocol you can use for this, albeit a complex one that's often overkill. JSON or just plain text are many times better choices.
You can use the function below to get content from your PHP script
public static String get(String from) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(from);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) return EntityUtils.toString(resEntityGet);
} catch (Exception e) {
Log.e("", e.toString());
}
return null;
}

Categories

Resources