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);
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 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();
I am currently doing a project in which I have to request data from the metabolite database PubChem. I am using Apache's HttpClient. I am doing the following:
HttpClient httpclient = new DefaultHttpClient();
HttpGet pubChemRequest = new HttpGet("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid="
+ cid + "&disopt=SaveXML");
pubChemRequest.getAllHeaders();
System.out.println(pubChemRequest);
HttpResponse response = null;
response = httpclient.execute(pubChemRequest);
HttpEntity entity = response.getEntity();
pubChemInchi = EntityUtils.toString(entity);
The problem is that this code streams the entire XML file:
<?xml version="1.0"?>
<PC-Compound
xmlns="http://www.ncbi.nlm.nih.gov"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:schemaLocation="http://www.ncbi.nlm.nih.gov ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem.xsd">
etc.
What I want is that I can request, for example, the PubChem ID and it will paste the value that corresponds to that ID. I have found that this can be done with the native Java method, but I need to use the HttpClient for this.
With the native Java, it would be done like this:
cid = 5282253
reader = new PCCompoundXMLReader(
new URL("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=" + cid + "&disopt=SaveXML").newInputStream())
mol = reader.read(new NNMolecule())
println "CID: " + mol.getProperty("PubChem CID")
(Note: This piece of code was written in Groovy, but it also works in Java after some adjustments)
So, if anyone can help me out, that would be great:)
There are multiple ways to do this.
If you want to turn the response into a bean and dont expect the the structure of the response to change I'd look at using XStream.
Another option is using the SAX parser directly.
Ofcourse the quick and dirty approach is to turn your responses content into a bufferedReader. Then feed that reader into the XMLReader you are using.
An example using you code from above would be:
HttpClient httpclient = new DefaultHttpClient();
HttpGet pubChemRequest = new HttpGet("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid="
+ cid + "&disopt=SaveXML");
pubChemRequest.getAllHeaders();
System.out.println(pubChemRequest);
HttpResponse response = null;
response = httpclient.execute(pubChemRequest);
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
cid = 5282253
reader = new PCCompoundXMLReader(br)
mol = reader.read(new NNMolecule())
println "CID: " + mol.getProperty("PubChem CID")
Googling for RESTful webservice clients or XMLReaders should give you plenty more information on this subject
Try using NameValuePair
For eg:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("username", user123));
nameValuePairs.add(new BasicNameValuePair("password", pass123));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
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);