0

I have an endpoint /test which expects Map :

 @POST("/hello")
    @PermitAll
    public JSONObject test(Map param) throws JsonParseException {
    String elementName = param.get("name").toString();
    String elem = param.get("elem").toString();
        JSONObject json=new JSONObject();
        try {
            json.put("id",1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

And I'm sending asynchronous POST (postin JSON) using AsyncHttpClient:

public static void asyncCallPost(JSONObject jsonData) throws Exception {
        AsyncHttpClient client = new AsyncHttpClient();
        try { 
            Response response = client.preparePost(url) 
                    .addHeader("Content-Type", "application/json") 
                    .addHeader("Content-Length", "" + jsonData.length()) 
                    .setBody(jsonData.toString()).execute().get(); 
            if (response.getStatusCode() != 200) { 
                throw new Exception("Error ");
            } 
        } finally { 
            client.close(); 
        } 
    }

But I am getting java.lang.NullPointerException. Is it because I don't pass any Map to /hello? If so how make POST with jsonData as Map to the endpoint?

AJ-B29
  • 215
  • 1
  • 11

2 Answers2

0

I cannot tell without further information however I suspect that the following needs to change;

String elementName = param.get("name").toString();
String elem = param.get("elem").toString();

to

String elementName;
if(param.get("name") != null){
   elementName = param.get("name").toString();
}
String elem;
if(param.get("elem") != null){
   elem = param.get("elem").toString();
}

The reason being the param.get("name") is returning a null which you are attempting to run toString on, hence the null pointer exception.

Steve
  • 469
  • 4
  • 12
0

You're setting a JSON string to the body, that's why the Map is null or empty or full of garbage (I didn't check myself).

The Map is a representation of the key-value pairs that are POSTed. To have the Map non-empty, you would have to post e.g. name=myname&elem=myelement as type application/x-www-form-urlencoded.

Jakub Kotowski
  • 7,411
  • 29
  • 38