I am trying to make a POST with javax. Keep getting the 400 bad request response code. It suggests that there is something wrong with the json being sent(?) I have checked the json a hundred times, it looks pretty good to me. What am I missing?
enter code here
Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{ 'offset': 0, 'limit': 15, 'query': 'ad', 'search_type': 'global'}");
Response response = client.target("https:******/contacts/search")
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Accept", "application/json")
.header("authToken", ACCESS_TOKEN)
.post(payload);
Related
What is the difference with UniRest and Spring RestTemplate which is giving back a 400 Bad Request with apparently the same header and body sent ?
I try to reach the HubSpot API to create a BlogPost, but using RestTemplate I have a 400 Bad Request error, and using UniRest works alright (returns an OK response). However, I do not want to include a library just to make one REST call: I'd rather stick to RestTemplate.
The request data I need to send
HttpMethod: POST
URL: https://api.hubapi.com/content/api/v2/blog-posts?hapikey=*****************
Header: Content-Type: application/json
Body: (represented by a class instance as blogpostSendPost further down)
{
"name": "My first API blog post!",
"content_group_id": 351076997
}
Using RestTemplate
Setting up the request:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<BlogpostSendPost> request = new HttpEntity<>(blogpostSendPost, headers);
log(request.toString());
//LOG PRINT: <BlogpostSendPost(name=My first API blog post!, content_group_id=351076997),[Content-Type:"application/json"]>
OR in JSON
The .json() method converts my object in Json like you can see in the logs
HttpEntity<String> request = new HttpEntity<>(blogpostSendPost.toJson(), headers);
log(request.toString());
//LOG PRINT: <{"name":"My first API blog post!","content_group_id":"351076997"},[Content-Type:"application/json"]>
With .postForObject(): 400 Bad Request
BlogpostResponsePost answer = restTemplate.postForObject(
"https://api.hubapi.com/content/api/v2/blog-posts?hapikey=***********",
request,
BlogpostResponsePost.class);
With .exchange(): 400 Bad Request
BlogpostResponsePost answer = restTemplate.exchange(
"https://api.hubapi.com/content/api/v2/blog-posts?hapikey=**********",
HttpMethod.POST,
request,
BlogpostResponsePost.class);
Using UniRest: OK
HttpResponse<JsonNode> resp = Unirest
.post("https://api.hubapi.com/content/api/v2/blog-posts?hapikey=**********")
.header("Content-Type", "application/json")
.body(blogpostSendPost)
.asJson();
I am using PostMan to call my REST SpringBoot Application which is using theses Services : when I am calling the HubSpot API directly from PostMan it works fine, just like with UniRest lib.
Thanks for your help guys !!
Please refer https://community.hubspot.com/t5/APIs-Integrations/Getting-400-Bad-Request-when-trying-to-add-a-Blog-Post/td-p/306532
Instead of converting request object to json, pass request object directly. It worked for me.
// TRY 1: CONTACTS - RestTemplate - OK - contact is created (API V1)
HttpEntity request1 = new HttpEntity<>(contactSendList, headers);
ContactResponseInformations answer1 = restTemplate
.postForObject(
HubSpotConfiguration.URL_CREATE_CONTACT,
request1,
ContactResponseInformations.class);
log.info(answer1.toString()); // OK
I am calling a post request using Jersey rest client which contains no request body but contains authorization header. I am always getting 400 error. I tried from postman i got 200 response. Here is my code
ClientResponse response = null;
Client cliente=Client.create();
cliente.addFilter(new LoggingFilter(System.out));
WebResource webResource=cliente.resource("https://URL/token");
Builder builder = webResource.accept("application/json");
builder.type(MediaType.APPLICATION_JSON);
builder.header("Authorization", "Basic YbjjkwliOTQtNjRiYy00NWE5LWFhMzQtMTFhNDkyZZjNTVlOjZjYjk2OTMwNGE5YTQ3OTlhODVjZTM5MDFiMDEyMTI2";
builder.post(ClientResponse.class,Entity.json(""));
Don't use the way you are trying right now. Use HttpAuthenticationFeature from Jersey like this
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("username", "password");
final Client client = ClientBuilder.newClient();
client.register(feature);
If you are getting 200 success respone in postman and failure response in your application then you need to check your api with another api tester online tool. I had the same issue i put / at the last of end point.
I've tried in postman successfully,by adding Header"Content-Type=application/x-www-form-urlencoded" with x-www-form-urlencoded body.Apparently, this was my first time working on rest. Please advise me that below my code is correct or not. Thank You.
RestAssured.baseURI = AssignConfig.app.getProperty("RestURL");
Response request = RestAssured
.given()
.config(RestAssured.config()
.encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs("x-www-form-urlencoded", ContentType.URLENC)))
.contentType("application/x-www-form-urlencoded; charset=UTF-8")
.header("Content-Type", "application/x-www-form-urlencoded")
.formParam("login","userName")
.formParam("password","password")
I create a client in java and want to get the query results from index but got the 406 error:
"Content-Type header [text/plain] is not supported","status":406.
Java platform: 1.6
ES version: 6.0
Below is the code snippet:
Client clientInstance = Client.create();
clientInstance.addFilter(new HTTPBasicAuthFilter("", ""));
WebResource webResource =
clientInstance.resource("http://hostname:9200/indexname/_search");
ClientResponse response=webResource.entity(dsl).accept("application/json").get(ClientResponse.class);
String result = response.getEntity(String.class);
I use the dsl in Kibana and can get the correct query results. But it did not get the correct response in java and throw 406 error.
How can I fix this issue? Thanks very much!
You simply need to add another Content-type HTTP request header for the application/json mime type since you're sending some JSON and ES doesn't guess your content type anymore:
ClientResponse response = webResource
.entity(dsl)
.header("Content-type", "application/json") <--- add this
.accept("application/json")
.get(ClientResponse.class);
I am using the following code to consume a rest post service
Client client = ClientBuilder.newClient();
WebTarget target = client.target("wrong url");
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);
Response response = builder.post(Entity.entity(param, MediaType.APPLICATION_JSON), Response.class);
As expected I am getting error. and status code 400 Bad Request. But i am not getting the error message. when i run response.getStatusInfo() i get bad request but my server sends additional info.
when i call this using postman i get error info in the Body window.
So how do I get this error body info from the response object?
or any other way???
You get the response body as usual with Response#readEntity:
Read the message entity input stream as an instance of specified Java type using a MessageBodyReader that supports mapping the message entity stream onto the requested type.
Example:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("wrong url");
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);
Response response = builder.post(Entity.entity(param, MediaType.APPLICATION_JSON), Response.class);
String body = response.readEntity(String.class);
With Response#getStatusInfo you get only HTTP status, class and reason phrase.
I am new to Jersey and JAX-RS, but I believe this question is equivalent to Handling custom error response in JAX-RS 2.0 client library, which has much better answers.