PHP json_encode() returns nothing - java

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!

Related

HttpGet in Android/Java with GZip encoding

I am running MVC 4 on my server and to save a bit of data for my users I figured I would enable GZip encoding, to do this I simply used:
(C#)
Response.AddHeader("Content-Encoding", "gzip");
Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);
In my android application I use:
(Java)
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
When I use GZip the Java code nuts out and causes GC to run, I was never patient enough to wait for it to return.
When I took off GZip from the server it ran perfectly fine. The function to get the response returns straight away with no problem.
I tried adding this to the java code:
httpGet.addHeader("Accept-Encoding", "gzip");
With no success.
Question is, is there something I'm not getting? Can I not put the response in a stream if it is using GZip? Am I meant to use the stream and uncompress it after?
What am I doing wrong?
Instead of using
DefaultHttpClient client = new DefaultHttpClient();
you can use
ContentEncodingHttpClient client = new ContentEncodingHttpClient();
which is a subclass of DefaultHttpClient and supports GZIP content.
You need Apache HttpClient 4.1 for this.
If you have Apache HttpClient 4.2, you should use
DecompressingHttpClient client = new DecompressingHttpClient();
if you have Apache HttpClient 4.3, you should use the HttpClientBuilder

Posting to REST api using Java, specifically Android

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.

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

java : upload files to HTTP server using POST, server code issue?

I am new to java and I have to transfer file from Android application to server. I took help from the link
Uploading files to HTTP server using POST. Android SDK
<?php
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Its PHP code and works perfectly fine but I have to implement the server side code in Java not in PHP.
I googled and find the code from link enter link description here
InputStream in = request.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
while ((line = r.readLine())!=null) {
buf.append(line);
}
String s = buf.toString();
I am new to java so donot know how to write this code. I have NetBeans netbeans-7.1.1-ml-javaee installed.
Can somebody tell me that if this code is correct and how to put it in file or which type of file. I have created project but do not know how to put this code in file.
Edits:
Andriod code is working fine ... I want to develop Server code to get and save file
i hope this code can help u
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Image_url);
MultipartEntity mpEntity = new MultipartEntity();
File file = new File(selectedImagePath);
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("photo", cbFile);
mpEntity.addPart("user_id", new StringBody(SmallyTaxiTabbar.unique_ID));
mpEntity.addPart("password", new StringBody(SmallyTaxiTabbar.password));
post.setEntity(mpEntity);
HttpResponse response1 = client.execute(post);
HttpEntity resEntity = response1.getEntity();
String Response=EntityUtils.toString(resEntity);
Log.d("PICTUREServer Response", Response);
JSONArray jsonarray = new JSONArray("["+Response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
alert=(jsonobject.getString("alert"));
client.getConnectionManager().shutdown();
}
catch (Exception e) {
Log.e("TAGPost", e.toString());
}
where SmallyTaxiTabbar.unique_ID, password is parameter value
*i Hope this code can help u ! *
check if this library helps you. I have created wrappers for several http methods..
https://github.com/nareshsvs/android-libraries
The Apache Commons FileUpload library should help you process the content of the POST request in Java from a server point of view. It can be integrated with Servlets if required.
In particular, it will process the multipart/form-data content for you (which you would otherwise have to do manually if you were reading the request's InputStream directly line by line).

HTTPPost usage error to in execution method

I am using the following code to make a http client ,i am facing problem in execute method ,its getting stuck there.
public static final HttpHost target = new HttpHost("test.xyz.com", 443, "https");
public static void test()
{
HttpEntity responseEntity = null;
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("/xyz/test");
System.out.println("post is " +post.getRequestLine());
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
AuthScope authScope = new AuthScope(target.getHostName(), target.getPort());
System.out.println("auth scope is " +authScope);
client.getCredentialsProvider().setCredentials(authScope, credentials);
//i am passing a xml here
post.setEntity(new StringEntity(xml, "UTF-8"));
post.addHeader("Content-Type", "application/xml");
post.addHeader("Accept", "application/xml");
System.out.println("post " +post.getAllHeaders().length);
HttpResponse response = client.execute(target, post); //getting stuck here no response at all
System.out.println("response " +response.getStatusLine());
responseEntity = response.getEntity();
System.out.println("response entity " +responseEntity);
String responseXmlString = EntityUtils.toString(responseEntity);
System.out.println("response" +responseXmlString);
}
i am facing problem here
HttpResponse response = client.execute(target, post);
what might be wrong ?
The problem is the code is getting stuck in client.execut method its not moving furthur neither i am getting any response.Do i have to set any proxy?
Probably your request is not really 'stuck' but just waiting on a TCP connection timeout, which bu default could be quite lonkg - like 5 minutes or so. There should be a way to set timeout to shorter value - take a look at javadoc for your http client or just try to wait longer.
Also you can take a thread dump while your program is stuck to see where the thread is blocked (see jps and jstack utilities in Sun's JDK)
I think you first need to eliminate the possibility of your server misbehaving. Have you tried POSTing to that URL from outside of your program. Try something like this if you are on a unix-like system or are on windows and have cygwin:
cat <yourfile.xml> | curl -X POST -H 'Content-type: text/xml' -d #- https://test.xyz.com:443/xyz/test
If the POST is successful get a thread dump of your program and post it here for us to take a look.

Categories