Android从POST Http执行获取JSON返回错误

时间:2012-02-17 21:13:22

标签: android json http exception post

我目前正在尝试通过POST将数据发送到服务器,服务器正在处理数据并将其附加到JSON文件。我目前收到422错误,我已经收到它一段时间了。我的问题是:我如何在Java中收到JSON错误本身,以便我可以看到错误是什么。我所看到的只是一个HttpResponseException,并没有给我任何其他东西。感谢您的时间和提前帮助。

        HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(mPath);
        // Add your data
    try
    {
        List nameValuePairs = new ArrayList(4);
        httppost.setHeader("Authorization", Base64.encodeToString(new StringBuilder(bundleId).append(":").append(apiKey).toString().getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP));
        nameValuePairs.add(new BasicNameValuePair("state", "CA"));
        nameValuePairs.add(new BasicNameValuePair("city", "AndDev is Cool!"));
        nameValuePairs.add(new BasicNameValuePair("body", "dsads is assrawstjljalsdfljasldflkasjdfjasldjflasjdflkjaslfggddsfgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfddjflaskjdfkasjdlfkjasldfkjalskdjfajasldfkasdlfjasljdflajsdfjasdjflaskjdflaksjdfljasldfkjasljdflajsasdlfkjasldfkjlas!"));
        nameValuePairs.add(new BasicNameValuePair("title", "dsaghhhe fd!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        //HttpResponse response = httpclient.execute(httppost);
        //int status = response.getStatusLine().getStatusCode();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost, responseHandler);
        Log.v(TAG, "response: " + responseBody);
        //JSONObject response = new JSONObject(responseBody); 
        int f = 0;
    }
    catch(HttpResponseException e)
    {
        Log.e(TAG, e.getLocalizedMessage());
        Log.e(TAG, e.getMessage());
        e.printStackTrace();
    }

2 个答案:

答案 0 :(得分:2)

您可以使用预定义的Json类更方便地发送参数,如下所示:

    String jsonParam = null;
    try{
        JSONObject param = new JSONObject();
        param.put("state", "CA");
        param.put("city", "AndDev is Cool!");
        //and so on with other parameters

        jsonParam = param.toString();
    }
    catch (Exception e) {
        // TODO: handle exception
    }

并将帖子实体设置为:

if(jsonParam != null)
     httppost.setEntity(new StringEntity(jsonParam, HTTP.UTF_8));

答案 1 :(得分:1)

422错误说:Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors

您遇到UrlEncodedFormEntity

的问题