Seemingly simple question, but no obvious answer found online.
At this link, there is a tutorial on posting simple name value pairs to a file from within an android app. http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
What I want to do is post 'something' which on the receiving end (a php script) can be accessed as an array.
In PHP I want to receive:
$_POST['array']=array("key"=>"value","key2"=>"value2");
Being relatively new to android development, perhaps someone could elaborate on creating a similar thing in Java, and then how one cant send it - setEntity seems to only take namevaluepairs...
Many Thanks
You should use a JSON Wrapper both in Android App and your PHP server.
In PHP you should use json_decode(), like: $thingFromPost = json_decode($data).
In Java, there are many ways to create a JSONArray. A basic example would be:
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
JSONArray jsonArray = new JSONArray(list);
And after that, you just send your array with a HttpPost to your server.
StringEntity stringEntity = new StringEntity(jsonArray.toString());
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8"));
stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
HttpPost post = new HttpPost(url);
post.setEntity(stringEntity);
post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
If you need a detailed tutorial how to make requests using JSON in Android, follow this link.
Hope it helps!
If you want the entire, raw body of your POST to be the stringified array (and nothing else), I believe you should use a StringEntity instead of a UrlEncodedFormEntity.
So this:
String s = "asdf"; // replace this with your JSON string
StringEntity stringEntity = new StringEntity(s);
httpPost.setEntity(stringEntity);
I am not familiar with PHP, but conceptually on the receiving end you'll then do something like json.parse(request.full_body). Note that this (request.full_body or the equivalent) is very different from the common pattern of fetching a single value of the POST form like request['input_field1'].
However, reading your question I'm not entirely sure that this full_body approach is what you want. It looks to me like you want to access the data via the form variable 'array', as you indicate here:
$_POST['array']=array("key"=>"value","key2"=>"value2");
Note that you are not working with the entire POST body here, rather instead you are fetching the value of a single form variable called 'array' (I think, I don't really know PHP). If this is the case, then you should use NameValuePairs like something below:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("array", yourJSONArrayAsString));
This will post the array as a value associated with the form variable 'array' I believe.
Related
Goal
I am writing a program where a user's input is taken as a parameter and queried against an online API.
Problem
Oddly, I cannot get my parameter into my API successfully. The error I get is
"Could not look up user information; You have an error in your SQL syntax;" Which as it says plainly , is an SQL error. Therefore I was thinking there was a problem in passing my parameter since the application works when I hard code parameter and say "select name from table where id=1".
This is the parameter code and despite many edits and changes I got the same issue which caused me to look to my php even if everything works right in the browser.
HttpParams param = new BasicHttpParams();
ArrayList<NameValuePair> inputArguments = new ArrayList<NameValuePair>();
inputArguments.add(new BasicNameValuePair("id", idnum));
HttpClient client = new DefaultHttpClient(param);
HttpPost request = new HttpPost("http://myurl.com/DAIIS/getName.php");
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new UrlEncodedFormEntity(inputArguments, "UTF-8"));
HttpResponse httpResponse = (HttpResponse) client.execute(request);
Where I think the problem lie
I belives the problem lies in my select statement
<?php
header("Content-Type:application/json");
//Connect to DB
include ("dbcon.php");
//Run query
$para=$_GET['id'];
$sql=("SELECT name FROM class where stu_id=$para");
I say this because after stripping my API to the bare minimum the program's error was Could not look up user information; You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
but if i hard code the parameter (it works) or put something random like stu_id=$_GET['id']; it returns blank.
So is the way that I used this parameter incorrect for android? even if it works in the browser?
Thank you
As you asked for :
Just change '$_GET' to '$_POST',
As a side note
You can also check 'POST' request in browser, in order to do that add 'Rest client plugin' to your browser and you are done and have fun with api calls :)
I need to post data to webservice where I need to send a parameter along with JSON object in android . Is it possible to send both parameter and JSON object while posting data ?
My code is as folows:
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("token", "abc.org"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpPost.setEntity(JSON.toString);
Thanks in Advance
You can't call setEntity() twice like this. If your server is expecting POST content that is form-encoded, then you'll need to add your JSON object as one of the POST parameters. If your server is expecting the JSON object as the POST body, then it can't also be expecting any other parameters (this wouldn't be possible). It may be possible that it expects additional parameters in the query string part of the URL though. Check the API documentation of your server.
I have no code with me. I need to create a webservice that can fetch data from database, in JSON format. This data will be consumed in android. I don't know where to start from. It would be great if anyone could help, show me the way.
If you are proficient in .net, it's not a big deal to do that. At Android side you just do this way.
List<NameValuePair> parmeters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username",username));
parameters.add(new BasicNameValuePair("password",password));// These are the namevalue pairs which you may want to send to your php file. Below is the method post used to send these parameters
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url); // You can use get method too here if you use get at the .net side to receive any values.
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
At your .net side, you extract the data and send back the result by encoding it in json format. While at the android side again, you can get the input stream as shown above. From that input stream, you can get the json data.
For more details see this thread. If you still want any sources, then I might edit my answer with some sources. Hope this helps.
I'm doing an app that interacts with a mysql database with some php scripts. I would like to know if it is possible to send and array in a php POST from an android activity ?
This is th code I'm using for the moment :
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userID", String.valueOf(userID)));
but I think sending and array would be much better than sending one ID at a time.
I would generate a JSON/XML document. You can easily generate especially JSON objects in Android platform.
There are many examples about generating JSON in Android and reading/parsing JSON in PHP.
Hope this helps.
I saw a part of the solution in here :
enter link description here
In his example he simply does a for loop like this :
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//friendID is an array of friends ID
for (int i=0;i<friendID.length;i++){
nameValuePairs.add(new BasicNameValuePair("userAsked[]", String.valueOf(friendID[i])));
}
The thing is : how do I use it in my php file ? Is it as simple as that :
$asked[] = $_POST['userAsked[]'];
Seems a little bit too easy :s
I am implementing an android app in which I want to use some methods from a server (which was not implemented by me). Now when I try to make an http-post where I have to pass only String parameters everything works fine with a code like:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user[email]", email));
nameValuePairs.add(new BasicNameValuePair("user[password]", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
JSONObject response=new JSONObject(responseBody);
System.out.println("RESPONSE " + response.toString());
I get the response as a json object which I can easily use to take the attributes I wish.
Now there are methods that require non String values (integer, or boolean) as parameters. I cannot pass these arguments in a list such as List<NameValuePair> since this takes only Strings. I tried to pass it as a json object too but no success.
So my first question is if it is possible to have non String parameters in http post? And if yes, how should it be done? Eg if in the code above email was an integer and password a Boolean (in shake of the example), how should I handle them?
Thank you all in advance!
Sure, consider a file upload.
The file is binary (ok, consider uploading a picture if someone consider a text not to be binary enough)
the technique is a http-post
All http request parameters will come in as strings, but the server side code can convert them. The server could for example grab a JSON string from a request parameter and turn it into an object that contains any amount of serialized data. This could include integers, lists etc.
The implementation though will be dependent on that server side code. Both the client and server for example could use GSON to send objects and lists back and forth.
public void doPost(...)
{
String param = request.getParameter("someParam");
MyCustomObject myCustomObject = (MyCustomObject)gson.fromJson(param, MyCustomObject.class);
}