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.
Related
I am getting data from server by building a get request (HttpRequest). The data is not in Json format (when I open the link in a web browser, it says "This XML file does not appear to have any style information associated with it. The document tree is shown below.")
Since it is the case, when I call this line:
HttpRequest request = buildGetRequest("TreeLocation");
final LocationListResponse response = request.execute().parseAs(getResultType());
The app stops there, and I think it is because it does not regconize the resultType.
So, now I want to declare the content type as Json. Anyone knows how to declare the content type in Google http client library?
just convert your xml response into json using json library..and then you will get json response
use this link Convert XML to JSON object in Android
Edit 1:
you can add this and try
httpPost.setHeader("Content-type", "application/json");
for json respomse
Here session_key and user_id are strings. While ' search_data' is json.
I have used the namevalue pairs and json object. But while i m combining below request, it is not working together.
I want to create request for below Request :
session_key=71589h9f0ad7a830078a16706569fdee&search_data={"FavoritesUserID":"137","count":6,"start_index":-1,"subcat_id":["12","33","34","35","36","37","38","39","40","62","63"]}&user_id=137
While i am executing above request , i am getting below error all time:
Missing Parameters IN request.
can any one please help me out with proper request where first 2 parameters are only string while other is JSON Object object.
Thanks
The simplest solution will be to choose one type of parameters.
Either wrap all you parameters data as a json:
{
"height":26,
"age":21,
"data":
{
"ID":2173.
....
}
}
or treat all your parameters as strings by simply giving the json data a parameter name:
nameValuePairs.add(new BasicNameValuePair("data", createRequest.toString()));
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.
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);
}