Reputation: 1712
I need to create Jersey REST client. Here is my code:
ClientConfig clientConfig = new DefaultClientConfig();
Client client = Client.create(clientConfig);
client.addFilter(new HTTPBasicAuthFilter(user_id, api_key));
WebResource webResource = client.resource(uri);
String inputString = "{ \"subject\" : \"Test\", \"message\" : \"Hello\", \"recipients\" : \"[email protected]\" }";
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, inputString);
// check response status code
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
Above code gives me below error:
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 500
REST service is not developed by me. It is third party service. REST service says:
API can be accessed over HTTPS with Basic HTTP Auth (the Authentication header for the requests, very standard for REST-like API). API requires HTTP POST.
This is the CURL which is working fine:
curl -u user_id:api_key -d "subject=API%20Test&message=Hello&[email protected]" apiEndpointUri
Please help me on Jersey REST client.
Upvotes: 2
Views: 3644
Reputation: 1709
I think your service didn't accept the POST with JSON type.
You can try with Form URLEncoded type
MultivaluedMap<String, String> postBody = new MultivaluedMapImpl();
postBody.add("subject", "Test");
postBody.add("message", "Hello");
postBody.add("recipients", "[email protected]");
ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, postBody);
Upvotes: 1