JSON_ERROR_SYNTAX通过Android App发送Json请求

时间:2017-10-22 16:43:11

标签: php android json

我正在尝试使用我的Android应用程序发送Json Post请求。 但奇怪的事情发生了。

这是我的Android代码:

try {
        URL url = new URL(BASE_URL + params[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type","application/json");
        connection.connect();

        //JSonObject

        JSONObject json = new JSONObject();
        for(int i = 0 ; i < jsonValues.size(); i +=2){
            json.put(jsonValues.get(i), jsonValues.get(i + 1));
        }
        jsonValues.clear();


        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
        //String encoded= URLEncoder.encode(json.toString(),"UTF-8");
        output.writeBytes(URLEncoder.encode(json.toString(),"UTF-8"));
        output.flush();
        output.close();

        int HttpResult = connection.getResponseCode();
        if(HttpResult ==HttpURLConnection.HTTP_OK){
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                String lineDecoded = URLDecoder.decode(line, "UTF-8");
                sb.append(lineDecoded + "\n");
            }
            br.close();
            System.out.println(""+sb.toString());
            if(sb != null){
                return sb.toString();
            }else{
                return null;
            }


        }else{
            Log.d("ERRORRRRR",connection.getResponseMessage());
            return connection.getResponseMessage();
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
        return e.toString();
    } catch (IOException e) {
        e.printStackTrace();
        return e.toString();
    } catch (JSONException e) {
        e.printStackTrace();
        return e.toString();
    }

我的PHP代码是这样的:

$content = file_get_contents("php://input");
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0)
{
   throw new Exception('Request method must be POST!');
}

//Make sure that the content type of the POST request has been set to 
application/json

$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
    throw new Exception('Content type must be: application/json');
}

//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));

//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
echo($decoded);
exit;

当我使用我的Android应用程序发出请求并使用json_last_error()函数时,$ decoding为null我得到了JSON_ERROR_SYNTAX。

这是帖子请求的原始内容:

{"name":"test","identifier":"12345677"}

但我无法理解这是什么问题。事实上,当我尝试使用Advance Rest Client来模拟相同的请求时,它可以完美地工作,如下图所示。

enter image description here

1 个答案:

答案 0 :(得分:0)

我终于解决了我的问题......似乎是

readTextFile("menu.json", function(text){
   var data = JSON.parse(text);
   for(item in data["links"]){
   var key = data["links"][item]["url"];
   var file = data["links"][item]["file"];
   array_rooter[key] = function(){ 
      loader(file,'content'); 
   };
   routie(array_router);
}

实际上删除它并仅发送URLEncoder.encode(json.toString(),"UTF-8"); 一切都很完美