JSON - HTTP错误400.请求格式错误

时间:2014-09-08 08:11:22

标签: android

我在Android中有以下代码:

private void submit(JSONObject json) throws JSONException{
        String urlString = "...";

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(urlString);

        try {
            httppost.setHeader("json", json.toString());
            httppost.getParams().setParameter("jsonpost", json.toString());

            HttpResponse response = httpclient.execute(httppost);

            if(response != null)
            {
                InputStream is = response.getEntity().getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();

                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Result: " + sb.toString());
            } 
        } catch (Exception e) {
            System.out.println("error: " + e);
        }
    }

但是我在logcat中遇到了这个错误:

  

结果:错误请求

错误   请求


HTTP错误400.请求格式错误。

  

这是我的JSON:

{
    "form": {
        "sixthQuestionAnswer": "Snack/food",
        "ninthQuestionAnswer": "Yes , Rendy O/$ , 100 100",
        "fifthQuestionBudgetAnswer": "Will be",
        "thirdQuestionAnswer": "Several times (2–5x)",
        "secondQuestionAnswer": "No, reasons:",
        "fourthQuestionAnswer": "Very lucky",
        "secondQuestionSuggestionAnswer": "No answer",
        "tenthQuestionAnswer": "No choice",
        "firstQuestionAnswer": "Satisfied , Dissatisfied",
        "fifthQuestionAnswer": "7–12 kgs , Will be",
        "eighthQuestionAnswer": "Yes , Q2 , Y",
        "seventhQuestionAnswer": "1–5,000"
    },
    "ID": "RRR1"
}

有人可以告知发生了什么事吗?

2 个答案:

答案 0 :(得分:0)

为什么要在HTTP标头中发送json? 您应该在请求正文中发送它(但我不知道Web服务期望什么以及它期望数据在哪里)。

答案 1 :(得分:0)

我只需要使用它:

URLEncoder.encode(json.toString(), "utf-8");

并在Web服务中解码JSON。