I want to send a JSON to a PHP file that I have on my server, it works fine except when some field contains a special characters (accents, ñ, etc.).
Java file:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri);
JSONObject json = new JSONObject();
try {
// JSON data:
json.put("id_u", viaje.getID_U());
json.put("id_vo", viaje.getID_VO());
json.put("titulo", viaje.getTitulo());
[...]
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
PHP file:
$json = $_SERVER['HTTP_JSON'];
$data = json_decode($json);
$id_u = $data->id_u;
$id_vo = $data->id_vo;
$titulo = $data->titulo;
[...]
For example, if titulo = "día", $title is empty, but instead whether titulo = "example" works correctly.
I do not know how to convert to utf-8 before sending the items, I tried many things and nothing works for me. Any idea?
EDIT:
I could solve the problem. It was clear that the problem was the encoding. I solved by adding 2 lines to the code:
Java file:
// Post the data:
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
PHP file:
$json = $_SERVER['HTTP_JSON'];
$cadena = utf8_encode($json);
$data = json_decode($cadena);
thanks for your help! :)
Sounds like an encoding issue. Try setting the encoding like this:
HttpPost httppost = new HttpPost(builder.getUrl());
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
You can also force the proper encoding on your content like this. But that's probably not needed here:
// Add your data
httppost.setEntity(new UrlEncodedFormEntity(builder
.getNameValuePairs(), "UTF-8"));
Related
I'm sending data to php from java using JSON, using following code:
String url = "abc.php";
JSONObject json = new JSONObject();
json.put("msg", message); // message: "\ud83d\udc4d \ud83d\udc4e"
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
Log.i("resFromServer", resFromServer);
The PHP code is:
if( isset($_POST["json"]) ) {
$jsonDecode = json_decode($_POST["json"]);
$msg = $jsonDecode->{"msg"};
echo $msg;
}
But I'm getting output as ????
Whereas output should be 👍 👎
Is there some encoding issue? How can this be fixed?
Try , first converting the requested content to utf8
Those strings might not be UTF-16 actually. So do it safe and try
if( isset($_POST["json"]) ) {
$string=$_POST['json'];
$jsonDecode = mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string));
$jsonDecode = json_decode($jsonDecode);
$msg = $jsonDecode->{"msg"};
echo $msg;
}
I want to extract the string returned from java web service in java client. The string returned from java web service is as follows:
{"Name":"Raj Johri","Email":"mailraj#server.com","status":true}
Which is a Json string format. I have written client code to extract this string as follows:
public static void main(String[] args) throws Exception{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:8080/JsonWebService/services/JsonWebService/getData");
post.setHeader("Content-Type", "application/xml");
HttpResponse httpres = httpClient.execute(post);
HttpEntity entity = httpres.getEntity();
String json = EntityUtils.toString(entity).toString();
System.out.println("json:" + json);
}
I am getting following print on the console for json as:
json:<ns:getDataResponse xmlns:ns="http://ws.jsonweb.com"><ns:return>{"Name":"Raj Johri","Email":"mailraj#server.com","status":true}</ns:return></ns:getDataResponse>
Please tell me how to extract the string
{"Name":"Raj Johri","Email":"mailraj#server.com","status":true}
which is the actual message. Thanks in advance...
Well, The respons is as type of xml, and your json is in the <ns:return> node , so i suggest you to enter in depth of the xml result and simply get your json from the <ns:return> node.
Note:
I suggest you to try to specifying that you need the response as JSON type:
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
There is a dirty way to do this (beside the xml parsing way)
if you are getting the same XML every time,
you can use split()
String parts[] = json.split("<ns:return>");
parts = parts[1].split("</ns:return>");
String jsonPart = parts[0];
now jsonPart should contain only {"Name":"Raj Johri","Email":"mailraj#server.com","status":true}
I'm posting to the Wufoo api inside of an Android app and I am hitting a bit of a snag. My data does not seem to be formatting in a way that the server likes (or there is some other issue). Here is my code (note authkey and authpass are placeholders in the exmaple):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("Field17", "Some Value");
json = jsonObject.toString();
StringEntity postData = new StringEntity(json, "UTF8");
httpPost.setEntity(postData);
String authorizationString = "Basic " + Base64.encodeToString(
("authkey" + ":" + "authpass").getBytes(),
Base64.NO_WRAP);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Authorization", authorizationString);
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
The response I get back from the server looks like this:
{"Success":0,"ErrorText":"Errors have been <b>highlighted<\/b> below.","FieldErrors":
[{"ID":"Field17","ErrorText":"This field is required. Please enter a value."}]}
This is the response for a failure (obviously) which leads me to believe I'm doing the authentication correctly, and that it just doesn't like my JSON string, I've looked through the API docs which are located here:
http://www.wufoo.com/docs/api/v3/entries/post/
and by all accounts this should work? Any suggestions?
I would start by looking at this line:
StringEntity postData = new StringEntity(json, "UTF8");
It's "UTF-8", not "UTF8".
Note: I would suggest you using the HTTP.UTF_8 constant in order to avoid this kind of problem again.
StringEntity postData = new StringEntity(json, HTTP.UTF_8);
The Field17 may be of specific field type other than string.
After reading the document, I think you missed the point. The server accepted fields parameter from http post, not from a json string.
Your problem looks like this one.
So your request should like this:
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("Field17", "Some Value"));
httpPost .setEntity(new UrlEncodedFormEntity(postParameters));
Hope this can help.
I actually figured this out, this isn't a problem with the code anyone here gave me, it's the fact that I was sending the wrong header info. This must be a quirk of the Wufoo API.
If I use the BasicNameValuePair objects like what was suggestion by R4j and I remove the line
httpPost.setHeader("Content-type", "application/json");
everything works perfectly!
Thanks for all the help and I hope this helps anyone who is having trouble with the Wufoo API and Java.
I have a list of URLs which I need to get the content of.
The URL is with special characters and thus needs to be encoded.
I use Commons HtpClient to get the content.
when I use:
GetMethod get = new GetMethod(url);
I get a " Invalid "illegal escape character" exception.
when I use
GetMethod get = new GetMethod();
get.setURI(new URI(url.toString(), false, "UTF-8"));
I get 404 when trying to get the page, because a space is turned to %2520 instead of just %20.
I've seen many posts about this problem, and most of them advice to build the URI part by part. The problem is that it's a given list of URLs, not a one that I can handle manually.
Any other solution for this problem?
thanks.
What if you create a new URL object from it's string like URL urlObject = new URL(url), then do urlObject.getQuery() and urlObject.getPath() to split it right, parse the Query Params into a List or a Map or something and do something like:
EDIT: I just found out that HttpClient Library has a URLEncodedUtils.parse() method which you can use easily with the code provided below. I'll edit it to fit, however is untested.
With Apache HttpClient it would be something like:
URI urlObject = new URI(url,"UTF-8");
HttpClient httpclient = new DefaultHttpClient();
List<NameValuePair> formparams = URLEncodedUtils.parse(urlObject,"UTF-8");
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(formparams);
HttpPost httppost = new HttpPost(urlObject.getPath());
httppost.setEntity(entity);
httppost.addHeader("Content-Type","application/x-www-form-urlencoded");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity2 = response.getEntity();
With Java URLConnection it would be something like:
// Iterate over query params from urlObject.getQuery() like
while(en.hasMoreElements()){
String paramName = (String)en.nextElement(); // Iterator over yourListOfKeys
String paramValue = yourMapOfValues.get(paramName); // replace yourMapOfNameValues
str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
try{
URL u = new URL(urlObject.getPath()); //here's the url path from your urlObject
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
PrintWriter pw = new PrintWriter(uc.getOutputStream());
pw.println(str);
pw.close();
BufferedReader in = new BufferedReader(new
InputStreamReader(uc.getInputStream()));
String res = in.readLine();
in.close();
// ...
}
If you need to manipulate with request URIs it is strongly advisable to use URIBuilder shipped with Apache HttpClient.
try it out
GetMethod get = new GetMethod(url.replace(" ","%20")).toASCIIString());
Please use the URLEncoder class.
I used it in an exact scenario and it worked just fine for me.
What I did is to use the URL class, to get the part that comes after the host
(for example - at www.bla.com/mystuff/bla.jpg this would be "mystuff/bla.jpg" - you should URLEncode only this part, and then consturct the URL again.
For example, if the orignal string is "http://www.bla.com/mystuff/bla foo.jpg" then:
Encode - "mystuff/bla foo.jpg" and get "mystuff/bla%20foo.jpg" and then attach this to the host and protocol parts:
"http://www.bla.com/mystuff/bla%20foo.jpg"
I hope this helps
OK, few days ago I wrote a block of code in Java that sends post requests to a PHP file in order to store some data in a MySQL database and receive back simple json_encode() strings such as "error_101" responses from PHP and it worked just fine. Yesterday I reinstalled my XAMPP because I've had some problems with openssl PHP extention and now none of my json_encode() reponses return a value. I've checked the phpinfo() and it says that json support is enabled. To mention that values sent to PHP from JAVA are JSON objects as well and the json_decode() works just fine!
Here's my code to send responses from PHP to JAVA:
<?php
header('Content-type: application/json');
echo json_encode("error_101");
?>
Here's the code to get the response in JAVA
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
String url = "http://192.168.254.19/android/register.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
InputStream instream = entity.getContent();
InputStreamReader is_reader = new InputStreamReader(instream);
BufferedReader br = new BufferedReader(is_reader);
result = br.readLine();
Log.i("Read from server", result);
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
The response I'm getting is "<br />"
You sure you don't have some debug code somewhere up the chain that reads
echo $TesttVar1 . '<br />';
That would also stop the "header()" from working. Turn on ALL errors (error_reporting(E_ALL); ini_set('display_errors', 'on'); ) and that will show you the line the is output, if that's the case.
But to help weed it out if it is json_encode, just return "Error_101" without the function to test. But I don't think you're getting that far down the program.
json_encode needs an array. like
json_encode(array('status'=>'error_101'));
in this case:
header("Content-type: text/html");
echo json_encode("error_101");
it works.
in this other case:
header("Content-type: application/json");
echo json_encode("error_101");
it doesn't work.
It seems a bug!