java sending UTF-16 data to PHP not working - java

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;
}

Related

How to encode Post Data JSON in CloseableHttpClient APi

I have used the CloseableHttpClient APi for a Post call and Basic Auth for authorisation
private CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://example.com");
MyJson myJson = new MyJson(); //custom java object to be posted as Request Body
Gson gson = new Gson();
String param = gson.toJson(myJson);
StringEntity urlparam = new StringEntity(param);
String credentials = username + ":" + passwprd;
String base64Credentials = new String(Base64.getencoder().encode(credentials.getBytes()));
String authorizartionHeader = "Basic" + base64Credentials;
httppost.setHeader("Content-Type", "application/Json");
httppost.setHeader("Authorization", authorizartionHeader);
urlparam.setContentEncoding("UTF-8");
httppost.setEntity(urlparam);
httpclient.execute(httppost);
I am getting error
"Invalid UTF-8 middle byte"
I have encoded the JSON still the encoding is not working for other locales except English. How to encode the Post data.
I tried using the method
httppost.setEntity(new URLEncodedFormEntity(namevaluePair, "UTF-8")) but I don't have any Namevaluepair and if the add the Username-pswd in that then getting Null pointer response.
You should try to set everything as UTF-8
StringEntity urlparam = new StringEntity(param, StandardCharsets.UTF_8);
And add proper header
httppost.setHeader("Content-Type", "application/json;charset=UTF-8");

Code works in Xamarin Android but doestn't work in Java (HttpPost JSON)

I started developing in Xamarin, and then decided that license may be a bit expensive for playing around, so I'm transferring my code to java.
I have a small chunk that performs a POST with a JSON object, and it works in Xamarin and doest work in Java.
Xamarin:
var client = new HttpClient ();
var content = new FormUrlEncodedContent(new Dictionary<string, string>() {
{"action", "getEpisodeJSON"},
{"episode", "11813"}
});
client.DefaultRequestHeaders.Referrer = new Uri(link);
var resp = client.PostAsync("http://www.ts.kg/ajax", content).Result;
var repsStr = resp.Content.ReadAsStringAsync().Result;
dynamic res = JsonConvert.DeserializeObject (repsStr);
Android:
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost("http://www.ts.kg/ajax");
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("action", "getEpisodeJSON");
jsonObject.accumulate("episode", "11813");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.addHeader("Referer", "http://www.ts.kg");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
InputStream inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
String result;
if(inputStream != null)
result = convertInputStreamToString(inputStream);
What is a correct way to make such a POST in Android?
UPD
Current problem is that i'm getting an empty result string;
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
I ended up catching all requests of my device via Fiddle (good tutorial is here: http://tech.vg.no/2014/06/04/how-to-monitor-http-traffic-from-your-android-phone-through-fiddler/)
The difference was in cookie, so I used and HttpContex variable as described here:
Android HttpClient Cookie
And I also had a different Content-Type, so I set this header manually as this:
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

Why am I getting HTTP 400 bad request

I am using an HTTP client (code copied from http://www.mkyong.com/java/apache-httpclient-examples/) to send post requests. I have been trying to use it with http://postcodes.io to look up a bulk of postcodes but failed. According to http://postcodes.io I should send a post request to http://api.postcodes.io/postcodes in the following JSON form: {"postcodes" : ["OX49 5NU", "M32 0JG", "NE30 1DP"]} but I am always getting HTTP Response Code 400.
I have included my code below. Please tell me what am I doing wrong?
Thanks
private void sendPost() throws Exception {
String url = "http://api.postcodes.io/postcodes";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("postcodes", "[\"OX49 5NU\", \"M32 0JG\", \"NE30 1DP\"]"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
System.out.println("Reason : "
+ response.getStatusLine().getReasonPhrase());
BufferedReader br = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
result.append(line);
}
br.close();
System.out.println(result.toString());
}
This works, HTTP.UTF_8 is deprecated:
String url = "http://api.postcodes.io/postcodes";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
StringEntity params =new StringEntity("{\"postcodes\" : [\"OX49 5NU\", \"M32 0JG\", \"NE30 1DP\"]}");
post.addHeader("Content-Type", "application/json");
post.setEntity(params);
Jon Skeet is right (as usual, I might add), you are basically sending a form and it defaults to form-url-encoding.
You could try something like this instead:
String jsonString = "{\"postcodes\" : [\"OX49 5NU\", \"M32 0JG\", \"NE30 1DP\"]}";
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
post.setEntity(entity);

Android: HttpPost not work

Hi guy's (sorry for my english error :P ) i have a problem, I'm trying to post a variable (id_art) to a php page, the problem is that I can't understand if the variable is not sent properly, or if I read it wrong php side.
JAVA CODE:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myurl);
StringBuilder builder = new StringBuilder();
String json, result = "";
//Build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("id_articolo", id_art);
//Convert JSONObject to JSON to String
json = jsonObject.toString();
//Set json to StringEntity
StringEntity se = new StringEntity(json);
//Set httpPost Entity
httpPost.setEntity(se);
//Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
//Receive response as inputStream
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
//Convert input stream to string
if (statusCode == 200){
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line="";
while ((line = reader.readLine()) != null) {
builder.append(line);
result = builder.toString();
}
System.out.println("DEBUG"+" "+result);
PHP CODE
<?php
include_once('configurazione.php');
header("Content-Type: application/json");
mysql_set_charset('utf8');
$value = json_decode(stripslashes($_POST),true);
var_dump($value);
?>
result is NULL... Why ????
Tnks 4 help
EDIT 1
I try to edit my php code replacing
this : json_decode(stripslashes($_POST),true);
with: $value = json_decode($_POST);
But the result is the same.. NULL
EDIT 2
I try to replace
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = json_decode(file_get_contents('php://input'));
echo $value ;
but result is NULL
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = file_get_contents('php://input');
var_dump(json_decode($value , true));
try with this
in .JAVA
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", yourJson.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
in .PHP
$value = $_POST['json'];
var_dump(json_decode($value , true));
I believe you cannot simply send StringEntity, because POST parameters are expected to be key=>value pairs. That means you need to give a name to your parameter, let's say json.
Then you can do this:
JSONObject jsonObject = new JSONObject();
// here you can set up the data
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", jsonObject.toString()));
// here you can add more POST data using nameValuePairs.add()
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
On the PHP side, you'll just do
$value = json_decode($_POST['json'], true);
var_dump($value);

Send special characters in JSON from android to PHP

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"));

Categories