I am trying make a JSON call to a server using HttpClient API. The code sinppet is shown below.
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpPost(URLString);
HttpResponse response = httpClient.execute(httpPost);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("method", "completeUserLogin"));
String[] params = new String[]{"100408"};
response = httpClient.execute(httpPost);
I want to add params to nameValuePairs. BasicNameValuePair class does not allow you to add arrays. Any thoughts?
Thanks in advance!
Look at this . Here they pass the array in BasicNameValuePairs.Here the colours is the array which we are going to send on a server. You should use your array varible instead of colours.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("colours[0]","red"));
nameValuePairs.add(new BasicNameValuePair("colours[1]","white"));
nameValuePairs.add(new BasicNameValuePair("colours[2]","black"));
nameValuePairs.add(new BasicNameValuePair("colours[3]","brown"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(httpPost);
If you are posting data in json format then you should not post params like this. Instead create a JSONObject put these values in that json object, and get a string from that json object and then create a StringEntity, and set this Entity to HttpPost object.
Creating JSONObject for the Request:
JSONObject json=new JSONObject();
json.put("method", "completeUserLogin");
JSONArray arr= new JSONArray();
arr.put("100408");
json.put("params", arr);
String params=json.toString();
Related
I want to get the JSON data from solarwinds orion rest api and have to write those JSON data in excel file.
I'm assuming you need a java program to send a post request to an API endpoint. ApacheHTTP library to the rescue. You can read more from the documentation here. Even more information in the official apache website
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream instream = entity.getContent()) {
// do something useful
}
}
Taken from this answer
I've been using lots of HTTP posts in my apps recently and I've always been using this template:
HttpPost httpPost = new HttpPost(server);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","John"));
nameValuePairs.add(new BasicNameValuePair("age",13+""));
...
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpClient.execute(httpPost);
And on the server's PHP script:
$name = $_POST['name'];
$age = $_POST['age'];
...
This has always worked perfectly. However, recently I got a request that the data should actually be a JSON itself which would contain all those key-value pairs.
To be more explicit, the PHP script has been written to do this:
$json = $_POST['data'];
$name = $json['name'];
$age = $json['age'];
...
While this is an awkwardly simple modification, I can't seem to make it work in the Android code, i.e. I can't find the correct way to add the JSON to the HTTP data.
I'm doing this:
JSONObject json = new JSONObject();
json.put("name", "John");
json.put("age", 13+"");
...
But what to do next?? How can I add this JSON to the HTTP with the key "data"?
I've tried this:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", json.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
But I'm not sure it's the right way to do it and also the server's response is signalling an error.
How should I do it? How should I GENERALLY add a JSONObject with a key, or even a JSONArray?
Thanks!
EDIT: Please don't send me to other SO links, I've looked and none is answering straight to my point.
Generally write json:
http://www.vogella.com/tutorials/AndroidJSON/article.html#androidjson_write
For your task, you don't need to put your json into a list. Just do
httpPost.setEntity(new UrlEncodedFormEntity(json.toString()));
//or else use this
httpPost.setEntity(new StringEntity(json.toString(), HTTP.UTF_8));
EDIT:
JSONObject json = new JSONObject();
json.put("name", "John");
json.put("age", 13+"");
JSONObject data = new JSONObject();
data.put("data", json.toString());
httpPost.setEntity(new UrlEncodedFormEntity(data.toString()));
I'm a newb in PHP world and I've problems parsing JSON in PHP. I want to POST data to PHP script with my Java client using Apache HttpClient 4.x and Gson.
My JSON:
[{"Knt_KntWatchId":"15","type":"INSERT","Knt_Nazwa1":"a"},{...},...]
I'm sending it with Java using HttpClient and Gson:
List<Contact> contacts = ...;
HttpPost post = new HttpPost(CONTACTS_SERVICE);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("key", AppConstants.KEY));
nameValuePairs.add(new BasicNameValuePair("data", new Gson().toJson(contacts)));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
On page:
if (isset($_POST['data'])) {
$data = $_POST['data'];
$json = json_decode($data, true);
var_dump($json);
var_dump($data);
What I'm getting is:
NULL string(3651) "[{\"Knt_KntWatchId\":\"15\",\"type\":\"INSERT\",\"Knt_Nazwa1\":\"a\"},...
How can I get it working?
PHP 5.2 - can't use json_last_error()
try with stripslashes()
$string = stripslashes('[{\"Knt_KntWatchId\":\"15\",\"type\":\"INSERT\",\"Knt_Nazwa1\":\"a\"}]');
print_r(json_decode($string));
so il will be
$json = json_decode(stripslashes($data), true);
Im a newbie at android coding and I looked around a little to try to find a solution to my problem. The web-site I want to send the data has a form. I want to collect data from my activity in edittext fields and send it to the Web form and submit the web-form.
After some reading online I am across the below method. Can someone tell me if this is correct? If the webform has a field called "name" (I can access the site source). And the user enters "John Doe", So the NameValue pair will be "name","John Doe" right?
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),10000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(),10000);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name1", "value1"));
nameValuePairs.add(new BasicNameValuePair("name2", "value2"));
nameValuePairs.add(new BasicNameValuePair("name3", "value3"));
// etc...
try{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
}
catch(Exception e)
{
}
Yes, you are submitting the data via post.
Just in case you don't know this: You should post the data to the "form action" page.
Yes, what ever data you want to send you need to add to nameValuePairs
nameValuePairs.add(new BasicNameValuePair("name", "Jhon Deo"));
I've generate an HTMLPost Request containing a JSON object in java and would like to parse it in PHP.
public static String transferJSON(JSONObject j) {
HttpClient httpclient= new DefaultHttpClient();
HttpResponse response;
HttpPost httppost= new HttpPost(SERVERURL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
}
And on the server
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// input = "json=%7B%22locations%22%3A%5B%7B%22..."
$input = file_get_contents('php://input');
// jsonObj is empty, not working
$jsonObj = json_decode($input, true);
I guess this is because the JSON special characters are encoded.
The json_decode return empty response
Any idea why ?
Instead of POSTing an application/json entity, you are actually posting an HTTP form entity (application/x-www-form-urlencoded) with a single value pair json=(encoded json).
instead of
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Try
httppost.setEntity(new StringEntity(j.toString(),"application/json","UTF-8"));
That's by design: you are accessing the raw POST data, which needs to be URLencoded.
Use urldecode() on the data first.
Try this:
//remove json=
$input = substr($input, 5);
//decode the url encoding
$input = urldecode($input);
$jsonObj = json_decode($input, true);