Question

I'm calling a web service using the following code:

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;
    }

}

The json data that should be send is (I have verified that is correctly created):

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

But I obtain always the result: 400: Bad request

But if I call the same ws from POSTMAN or other similar application I obtain the status 200: Ok that ensure that the ws woeks good.

So where is the error?

Was it helpful?

Solution

  1. Are you sure want to do a POST request?
  2. Are you missing any headers, like authorization?
  3. Try this:

    StringEntity se = new StringEntity(requestData.toString(), "UTF-8");
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top