1

I know it's an habitual question; but mine is really strange. I've done in another context exactly the same code where it works, but not on th

    String result = "";
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://192.168.1.145/test/getActivities.php");
    //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    //convert response to string
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    result=sb.toString();
    try{
        JSONArray jArray = new JSONArray(result);
        Log.e("log_tag", "lool");
        for(int i=0;i<jArray.length();i++){
            JSONObject json_data = jArray.getJSONObject(i);
            if (json_data.getString("friendly_url").toString().length() == 2){
                Sectors.add(new BasicNameValuePair(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
            }
            else if(json_data.getString("friendly_url").toString().length() == 3){
                Branchs.add(new BasicNameValuePair(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
            }
            else if(json_data.getString("friendly_url").toString().length() == 4){
                SBranches.add(new BasicNameValuePair(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
            }
            else{
                SBranches.add(new BasicNameValuePair(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
            }
            String[] lesSec = new String[Sectors.size()];
            for (int u = 0; u < Sectors.size(); u ++)
                lesSec[u] = jArray.getJSONObject(u).getString("title");
            setSectors(lesSec);
            Log.e("log_tag", lesSec[1]);

        }
    }catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
    }

}catch(Exception e){
    Log.e("log_tag", "Error in http connection "+e.toString());
}

So this is the PHP file

<?php
$response = array();
$response["success"] = 0;
$response["message"] = "No products found";//*/


@mysql_connect("host","user","");
@mysql_select_db("db");

$q=@mysql_query("SELECT title, friendly_url FROM table");
while($e=@mysql_fetch_assoc($q))
        $OUTPUT[]=$e;

print(json_encode($OUTPUT));
print_r ($OUTPUT);


@mysql_close();
?>

Can anyone see the problem? I tried to print the $OUTPUT and this is the kind of result

Array ( [0] => Array ( [title] => Activités de services autres et institutions 
                       [friendly_url] => 15 
                     ) 
        [1] => Array ( [title] => Batiment, travau ...etc
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
BiLLiXx
  • 23
  • 1
  • 7
  • 1
    Can you attach an example of JSON response you're trying to parse? – Egor May 10 '16 at 09:11
  • Have you tried using `echo` in php ? – Shree Krishna May 10 '16 at 09:12
  • Please dont use [the `mysql_` database extension](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), it is deprecated (gone for ever in PHP7) Specially if you are just learning PHP, spend your energies learning the `PDO` database extensions. [Start here](http://php.net/manual/en/book.pdo.php) – RiggsFolly May 10 '16 at 09:12
  • Dont hide error with the `@` if you have errors fix them – RiggsFolly May 10 '16 at 09:15
  • Try removing the `print_r ($OUTPUT);` as that will also be sent to the browser as part of the response – RiggsFolly May 10 '16 at 09:16
  • If you want to check the contents of the array use something like `file_put_contents('debug.txt', print_r($OUTPUT, true) );` – RiggsFolly May 10 '16 at 09:17
  • Ok; echo will cause me problems cuz it'll be sent with JSON response to Java; so ... For the @; I deleted it, and nothing is shown print_r was just to show results; even without it, I got same error – BiLLiXx May 10 '16 at 09:18
  • `print(json_encode($OUTPUT));` would be much more interesting. Is the JSON string somehow truncated at the end? – Pinke Helga May 10 '16 at 09:25
  • In the other part where it works; here is the result: [{"login":"admin","pass":"0e8efb6206ee273d760d0673"} ...etc Why it's not the same type of array , – BiLLiXx May 10 '16 at 09:27
  • Thank you for the password hash :) We want to see the result where it does **not** work. Everything other is useless. – Pinke Helga May 10 '16 at 09:30
  • Yah, the result where it does NOT work is the last part of code in my post :) PS: try to translate the password :p – BiLLiXx May 10 '16 at 09:34
  • Why not? Is it "F\*CK"? :D Can you upload somewhere the full raw (*erroneous*) data coming from PHP script? Or is there some sensible data content? – Pinke Helga May 10 '16 at 09:37
  • No, it's not so sensible where it does not work, this is a part of result from PHP (it's too long) 'code' (Array ( [0] => Array ( [title] => ROOT [friendly_url] => ) [1] => Array ( [title] => Activités de services autres et institutions [friendly_url] => 15 ) [2] => Array ( [title] => Batiment, travaux publics et hydraulique [friendly_url] => 05 ) [3] => Array ( [title] => Cuirs, chaussures et maroquinerie [friendly_url] => 02 ) [4] => Array ( [title] => Etudes,engineering et services financiers [friendly_url] => 10 )) – BiLLiXx May 10 '16 at 09:42
  • This does not look like JSON. – Pinke Helga May 10 '16 at 09:45
  • it's what browser shows me due to a print_r ($OUTPUT); – BiLLiXx May 10 '16 at 09:47
  • You should inspect the **JSON** result in raw source code mode. You could also try console command `wget --save-headers www.example.com` to get a complete raw data view of the reply. – Pinke Helga May 10 '16 at 09:58

2 Answers2

0

Try header('Content-Type: application/json'); before any output has been sent.

As you show in your Answer, the result you got is actually not JSON!

See how JSON should look like:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

source: http://json.org/example.html

An array looks like: [ "one", "two", "three" ]

Remove the print_r from your PHP script, it does not produce valid JSON format and succeeding text after a JSON string invalidates the output at all.

After correcting that issue you should also inspect, what the PHP functions mb_internal_encoding and mb_http_output return and compare it to the expected encoding in java.

Pinke Helga
  • 6,378
  • 2
  • 22
  • 42
0

Well; if anybody has the same problème with special characters, I've found the solution It's in the PHP; all what u have is encoding the result with special items like that :

while($e=@mysql_fetch_assoc($q)){
    $e['title'] = mb_convert_encoding($e['title'], 'UTF-8', 'pass');
    $OUTPUT[] = $e;
}

I don't know why, but it works !

BiLLiXx
  • 23
  • 1
  • 7