Search code examples
postjerseydropwizardapi-designjersey-client

Post json to external api


I've just started using Drropwizard and want submit json data to POST method.

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String newPost(){
    Client client = ClientBuilder.newClient();

    String input = "{"version":"v1","buildTime":"2017-06-06"}";

    //call external api with json_input


    return result;
}

So I want to post the input (raw json) to external api.

using client.target("https://path_to_external_api").request().get(String.class); works fine for GET method but not sure how to implement POST

Any comments/suggestions is appreciated.


Solution

  • For the reference, I ended up using Jersey client like this.

    list of imports:

    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.core.Response;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    

    using the client inside @POST method in my resource:

        Client client = ClientBuilder.newClient();
    
        WebTarget tar = client.target("https://path_to_external_api");
        Response res =  tar.request().accept(MediaType.APPLICATION_JSON)
                .post(Entity.entity(json_input, MediaType.APPLICATION_JSON), Response.class);
        return res;