简体   繁体   中英

Parse PHP json UTF-8 to android

I want to parse Json from php file to androiud. The content of the PHP page is in UTF-8 format but when I run the app in Android Studio Manager I got this error :

08-06 16:24:58.856      275-282/androidhive.example.com.sigar3 D/dalvikvm﹕ GC_FOR_MALLOC freed 2057 objects / 135880 bytes in 65ms
08-06 16:24:59.196      275-282/androidhive.example.com.sigar3 D/Response:﹕ > ��������������V*(�O)M.)V���V�K�MU�R
    ��+.��S��f&�DLLM
����ĒԔ��%��Ҝ�҂�Z�1�ř
    N9���H�q���(�&'��fX�����������2��������
08-06 16:24:59.206      275-282/androidhive.example.com.sigar3 W/System.err﹕ org.json.JSONException: Value ��������������V*(�O)M.)V���V�K�MU�R of type java.lang.String cannot be converted to JSONObject

but its valid and readable when I run the PHP code. Here is part of the php code :

<?php
header('Content-Type: text/html; charset=utf-8' );

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_config.php';
// connecting to db
$con = mysqli_connect(sqlhost, sqluser, sqlpw, sqldb);
mysqli_query($con, "SET NAMES 'utf8'");
mysqli_query($con, 'SET CHARACTER SET utf8');

// get all products from products table
$result = mysqli_query($con, "SELECT *FROM fees");
// check for empty result
if (mysqli_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["products"] = array();
    while ($row = mysqli_fetch_array($result)) {
        // temp user array
        $product = array();
       // $product["pid"] = $row["pid"];
        $product["name"] = $row["name"];
        $product["price"] = $row["price"];
        $product["created_at"] = $row["created_at"];
        $product["updated_at"] = $row["updated_at"];

        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?>

Here is makeservicecall android class

public String makeServiceCall(String url, int method,
                                  List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                }

                httpResponse = httpClient.execute(httpPost);
                httpResponse.setHeader("Content-Type", "text/html;charset=uft-8");

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity, HTTP.UTF_8);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;

I use it this way

  String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);


        Log.d("Response: ", "> " + jsonStr);

How should I solve this ?!

I took a quick look at my project and found this comment at the top of the PHP file:

//Android will silently reject my response if it is
//mislabelled as "text/html".
header("Content-Type: application/json;charset=utf-8");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM