无法从Android应用程序调用REST ws

时间:2014-03-19 12:57:42

标签: android web-services android-json

我正在使用以下代码调用Web服务:

protected Boolean doInBackground(Void... params) {
    int resCode;        

    String uri = "http://myServer:8080/api/activities/post";
    HttpPost request = new HttpPost(uri);
    request.setHeader("Content-Type", "application/json");
    request.setHeader("Accept","application/json");

    try{
        JSONStringer requestData = new JSONStringer()
           .object()
                .key("codeActivity").value("XLT-900")
                .key("firstValue").value("9")
                .key("secondValue").value("3")
           .endObject();

        StringEntity entity = new StringEntity(requestData.toString());
        request.setEntity(entity);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(request); 
        resCode = response.getStatusLine().getStatusCode();

        if (resCode == 200) {
            return true;
        }else{
            Log.i("doInBackground","resCode: "+resCode);
            return false;
        }           

    }catch(Exception ex){
        ex.printStackTrace();
        return false;
    }

}

应发送的json数据是(我已经验证已正确创建):

{"codeActivity":"XLT-900","firstValue":"9","secondValue":"3"}

但我总是得到结果: 400:请求不好

但是如果我从POSTMAN或其他类似的应用程序调用相同的ws,我获得状态200: Ok,以确保ws很好。

那么错误在哪里?

1 个答案:

答案 0 :(得分:0)

  1. 您确定要发布POST请求吗?
  2. 您是否遗漏任何标题,例如授权?
  3. 试试这个:

    StringEntity se = new StringEntity(requestData.toString(), "UTF-8");
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));