0

We want to sent a post request to an external API provider.

we know how to send a GET, and how to parse the JSON response.

We know how to send a JSON payload into the POST.

What we cant find an example of a good way to get request parameters into the body of a POST with jersey.

e.g. to send a really simple get request, we can do this:

private final Client theHttpClient;

ClientConfig clientConfig = new ClientConfig();
JacksonJaxbJsonProvider jacksonProvider = new JacksonJaxbJsonProvider();
jacksonProvider.setMapper(theObjectMapper);
clientConfig.register(jacksonProvider);
clientConfig.register(EncodingFilter.class);
clientConfig.register(GZipEncoder.class);
theHttpClient = ClientBuilder.newClient(clientConfig);


int param1 = 123134
String param2 = "this+is+a+test";

String url = "https://api.some.com?param1=" + param1 + "&param2=" + param2;
uri = new URI(url);

WebTarget webTarget = theHttpClient.target(uri);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
RESPONSE response = invocationBuilder.get(responseClass);

This code will send the params via get.

How would we get the params into a post request body?

we see there is an invocationBuild.post which looks like this:

    @Override
    public <T> T post(final Entity<?> entity, final Class<T> responseType)
            throws ProcessingException, WebApplicationException {
        return method("POST", entity, responseType);
    }

What is entity in this case? We assume we could manually create a text body with the params packed in it, but there must be a nicer way to do this, which will ensure no typos etc? E.g. something which takes a map, or even an addParam function?

John Little
  • 7,993
  • 14
  • 62
  • 108

0 Answers0