【问题标题】:Malformed JSON while making a POST call进行 POST 调用时 JSON 格式错误
【发布时间】:2017-05-09 15:33:51
【问题描述】:

当我通过 POST 请求向服务器发送 JSON 对象时,服务器返回错误消息。

代码:

public String sendStuff(String reqUrl,String arg1, String arg2){
    String response;
    try{
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("argument1",arg1);
        jsonObject.accumulate("argument2",arg2);
        String json = jsonObject.toString();
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(URLEncoder.encode(json,"UTF-8"));
        out.flush();
        out.close();

        int HttpResult = conn.getResponseCode();
        if(HttpResult == HttpURLConnection.HTTP_OK){
            response = convertStreamToString(conn.getInputStream());
            return response;
        }
    }catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

错误信息:

{"ERROR":"JSONObject 文本必须在 1 [字符 2 第 1 行] 处以 '{' 开头"}

根据 RESTful 服务,只有当 JSON 格式错误时才会返回此错误消息。我已经通过 Chrome 扩展程序手动测试了该服务,它可以正常工作。

我认为应该不会有错误,因为我是通过 org.json 包中的方法直接将 JSON 转换为字符串。

我搜索了解决方案,但找不到。

【问题讨论】:

    标签: java android json rest post


    【解决方案1】:

    您不需要对从json.toString() 返回的String 中的数据进行 URLEncode。您应该能够将 String 本身作为 UTF-8 编码的字节流进行流式传输。对对象进行 URL 编码会将特殊的 JSON 终端字符(例如“{”)转换为其百分比编码的等效字符(例如 %7B),这不适用于 HTTP 请求的正文。

    要考虑的另一件事是,您实际上并不需要 DataOutputStream 来处理这种事情 - 输出应该是表示 UTF-8 编码的 json 文档的字节流,而 DataOuputStream 用于转换Java 原始对象到字节流。你已经有了一个字节流,所以你只需要把它发送到OutputStream...

        final String json = jsonObject.toString();
        final OutputStream out = new conn.getOutputStream();
        out.write(json.getBytes("UTF-8"));
        out.flush();
        out.close();
    

    【讨论】:

      【解决方案2】:

      添加标题试试这个:

      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Content-Type", "application/json");
      

      【讨论】:

      • 我认为应该可以。否则尝试 > conn.setRequestProperty("Accept", "application/json; charset=utf-8"); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
      • 不能解决我的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      • 2014-07-26
      • 2020-09-10
      • 1970-01-01
      • 2015-09-26
      相关资源
      最近更新 更多