Android中的HTTP 422 GET错误

时间:2013-02-08 02:01:17

标签: java android

我正在尝试向服务器执行GET请求,该服务器返回一个JSON文件。但我在HTTP statusLine / 422中收到错误。任何人都知道原因。下面我将展示我的工作方式

public void testConverteArquivoJsonEmObjetoJava() {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(
            "http://safe-sea-4024.ppooiheroku4554566adffasdfasdfalaqwerpcp.com/crimes/mobilelist");

    get.setHeader("Accept", "application/json");
    get.setHeader("Content-type", "application/json");

    get.getParams()
            .setParameter("token",
                    "0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJ88888a6JhMs=");

    HttpResponse httpResponse;
    try {
        httpResponse = httpClient.execute(get);
        String jsonDeResposta = EntityUtils.toString(httpResponse
                .getEntity());

        System.out.println();

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:1)

通常,您不会使用Content-Type请求指定GET标头。此标头告诉服务器如何解释消息中包含的实体。即使GET不能包含正文,服务器端也可能期望JSON实体。尝试删除Content-Type标题。

我尝试了你巧妙改变的网址并让它工作正常。但是,当我指定不同的令牌查询参数时,我确实得到了422。由于状态行缺少一个短语,我认为Ruby应用程序正在生成它。

答案 1 :(得分:0)

我设法解决了这个问题。我传递的参数错误了。根据这篇文章[博客]:How to add parameters to a HTTP GET request in Android?“链接”。这种方法用于我的POST请求

这种方法是正确的

 public void testConverteArquivoJsonEmObjetoJava() {
    List<NameValuePair> params = new LinkedList<NameValuePair>();

    params.add(new BasicNameValuePair("token","0V1AYFK12SeCZHYgXbNMew==$="));

    String paramString = URLEncodedUtils.format(params, "utf-8");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(
            "http://safep.com/crimes/mobilelist" + "?"
                    + paramString);
    HttpResponse httpResponse;
    try {

        httpResponse = httpClient.execute(get);
        String jsonDeResposta = EntityUtils.toString(httpResponse
                .getEntity());

        System.out.println();

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}`