I have taken the request code from
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
String json = String.format("{'sex': %s,'age': %d,'evidence': []}", gender, age);
RequestBody body = RequestBody.create(mediaType, json);
Request request = new Request.Builder()
.url("https://api.infermedica.com/covid19/diagnosis")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "*/*")
.addHeader("App-Id", "XXXXXX")
.addHeader("App-Key", "XXXXXXXXXXXXXXXXXXXXX")
.addHeader("User-Agent", "PostmanRuntime/7.19.0")
.addHeader("Accept", "*/*")
.addHeader("Cache-Control", "no-cache")
.addHeader("Postman-Token", "58fbac21-182b-41e0-bceb-0905d0605858,cd9580e6-f262-4440-ba33-b85877dd087c")
.addHeader("Host", "api.infermedica.com")
.addHeader("Accept-Encoding", "gzip, deflate")
.addHeader("Content-Length", "56")
.addHeader("Connection", "keep-alive")
.addHeader("cache-control", "no-cache")
.build();
com.squareup.okhttp.Response response = client.newCall(request).execute();
I am attempting to make a post request. I have successfully run the request in postman. And I have copied the code from postman. But when I run the request in java I get a 400 Bad Request. And I dont know why because all of the headers and the body is exactly the same as in postman.
You are missing quotes for Sex in your input
Confirmed here https://developer.infermedica.com/docs/covid-19
curl "https://api.infermedica.com/covid19/diagnosis" \
-X "POST" \
-H "App-Id: XXXXXXXX" -H "App-Key: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-H "Content-Type: application/json" -d '{
"sex": "male",
"age": 30,
"evidence": []
}'
Related
I'm trying to make a request where I pass some parameters in the Body, as shown in the image.
Example Image
Example:
Key: file[], Value: "xml", Content-Type: application/xml Key: query, Value: {"boxe/File": false}, Content-Type: application/xml
I'm getting a Bad Request error, I think my code isn't right. Follow how it is being done
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file[]", xml, RequestBody.create(null, "application/xml"))
.addFormDataPart("query", "{\"boxe/File\": false}", RequestBody.create(null, "application/xml"))
.build();
Request request = new Request.Builder().url(endPoint).addHeader("x-integration-key", integrationKey)
.addHeader("Authorization", "Bearer " + token)
.post(requestBody).build();
Managed to solve it, the order of the parameters were wrong,
follow the correct order
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file[]","", RequestBody.create(MediaType.parse("application/xml"), xml))
.addFormDataPart("query", "", RequestBody.create(MediaType.parse("application/json"), boxFileJson))
.build();
I'm able to consume APIs (OAuth 1.0 Authorization & signature method as HMAC-SHA256) in POSTMAN, but not working JAVA (maven project).
Generated code from POSTMAN with OkHttp & Unirest libraries, both are not working. They give the following error.
403 Forbidden
I understand error is related to invalid authentication parameters. But not able to figure out what needs to be changed. Because same keys are working in Postman
OkHttp JAVA Code
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("application/json");
String url = "https://www.example.com?script=508&deploy=1";
String JSONpayload = "{}";
RequestBody body = RequestBody.create(mediaType, JSONpayload);
Request request = new Request.Builder()
.url(url)
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "OAuth realm=\"1111222_SB1\",oauth_consumer_key=\"xxxxxxxxx\",oauth_token=\"xxxxxxxx\",oauth_signature_method=\"HMAC-SHA256\",oauth_timestamp=\"1628747273\",oauth_nonce=\"xxxxxx\",oauth_version=\"1.0\",oauth_signature=\"xxxxxxxxxxx\"")
.addHeader("Cookie", "NS_ROUTING_VERSION=LAGGING")
.build();
Response response = client.newCall(request).execute();
Unirest JAVA Code
Unirest.setTimeouts(0, 0);
String url = "https://www.example.com?script=508&deploy=1";
String JSONpayload = "{}";
HttpResponse<String> response = Unirest.post(url)
.header("Content-Type", "application/json")
.header("Authorization", "OAuth realm=\"1114415_SB1\",oauth_consumer_key=\"xxxxxxxxxx\",oauth_token=\"xxxxxxxxxxx\",oauth_signature_method=\"HMAC-SHA256\",oauth_timestamp=\"1628747273\",oauth_nonce=\"xxxxxxxx\",oauth_version=\"1.0\",oauth_signature=\"xxxxxxxx\"")
.header("Cookie", "NS_ROUTING_VERSION=LAGGING")
.body(JSONpayload).asString();
Any kind of help is appreciated. Thanks in Advance.
I'm trying to create a POST request in rest assured java but receiving HTTP Status 400 – Bad Request. Have tried below two approaches and the same API is working fine in postman. I'm using 4.1.2 rest assured in pom.xml
curl --location --request POST
'http://localhost:8080//api/v1/planning/trips?pageNumber=1&pageSize=40'
--header 'authority: http://localhost:8080'
--header 'authorization: Bearer e8c108d6-c380-4715-849b-b6eccd8d2045'
--header 'origin: http://localhost:8080'
--header 'referer: http://localhost:8080'
--header 'Content-Type: application/json;charset=UTF-8'
--data-raw '{ "endPlacementTimestamp": 1594994096206, "startPlacementTimestamp": 1593525296206 }'
Approach 1:
RestAssured.baseURI="http://localhost:8080";
RequestSpecification httpRequest = RestAssured.given();
httpRequest.header("authority","http://localhost:8080");
httpRequest.header("authorization","Bearer e8c108d6-c380-4715-849b-b6eccd8d2045");
httpRequest.header("Content-Type","application/json;charset=UTF-8");
httpRequest.header("origin","http://localhost:8080");
httpRequest.header("referer","http://localhost:8080");
JSONObject requestParams = new JSONObject();
requestParams.put("endPlacementTimestamp", "1594994096206");
requestParams.put("startPlacementTimestamp","1593525296206");
httpRequest.body(requestParams.toJSONString());
Response response = httpRequest.request(Method.POST,"planning/trips?pageNumber=1&pageSize=40");
int statusCode = response.getStatusCode();
// Assert.assertEquals(statusCode, "200");
// Retrieve the body of the Response
ResponseBody body = response.getBody();
Approach 2:
String body= "{\n" +
" \"endPlacementTimestamp\": 1594994096206,\n" +
" \"startPlacementTimestamp\": 1593525296206\n" +
"}";
RestAssured.baseURI="http://localhost:8080//api/v1/";
Response response = given()
.contentType("application/json")
.header("authorization","Bearer e8c108d6-c380-4715-849b-b6eccd8d2045")
.header("origin","http://localhost:8080")
.header("referer","http://localhost:8080")
.body(body)
.post("planning/trips?pageNumber=1&pageSize=40");[![enter image description here][1]][1]
Here's a simplified version of it, I have added a JSONObject here so you don't hardcode the payload in the body()
RestAssured.baseURI = "http://localhost:8080";
RequestSpecification requestSpec = new RequestSpecBuilder().addHeader("authority", "http://localhost:8080")
.addHeader("authorization", "Bearer e8c108d6-c380-4715-849b-b6eccd8d2045")
.addHeader("origin", "http://localhost:8080").addHeader("referer", "http://localhost:8080")
.addHeader("Content-Type", "application/json").build();
JSONObject payload = new JSONObject();
body.put("endPlacementTimestamp", 1594994096206L);
body.put("startPlacementTimestamp", 1593525296206L);
given().log().all().spec(requestSpec).queryParam("pageNumber", "1").queryParam("pageSize", "40").body(payload)
.post("/api/v1/planning/trips");
In approach1:
Put RestAssured.baseURI="http://localhost:8080//api/v1";
Last line .post("/planning/trips?pageNumber=1&pageSize=40");
Refer https://www.toolsqa.com/rest-assured/post-request-using-rest-assured/
I am trying to do a GET request with JAVA client using RestTemplate library, resulting in following error:
Exception in thread "main" org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden
When I am trying to hit the same URL by command line it is working fine. Posting the cURL command and Java code snippet here.
cURL :
curl -X GET -H "Authorization: Bearer ${TOKEN}" -H "Content-Type: application/json" https://xxxx-xxxx-xxxx {"key":"value"}
JAVA snippet :
String URL="https://xyz";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
//setting up the required headers
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("Authorization", "Bearer "+accessToken);
HttpEntity<String> entity = new HttpEntity<String>("body",headers);
//get request
ResponseEntity<String> responseEntity = restTemplate.exchange(URL, HttpMethod.GET, entity, String.class);
P.S - Is the issue because of the URL being a HTTPS one instead of HTTP ?
Add the user agent header, try and let us know if it works.
String URL="https://xyz";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
//setting up the required headers
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
//settting user agent
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
headers.set("Authorization", "Bearer "+accessToken);
HttpEntity<String> entity = new HttpEntity<String>("body",headers);
//get request
ResponseEntity<String> responseEntity = restTemplate.exchange(URL, HttpMethod.GET, entity, String.class);
I am trying to emulate this request using RestTemplate in Spring Boot
curl -X POST
'https://my.craftar.net/api/v0/image/?api_key=123456789abcdefghijk123456789abcdefghijk'
-F "item=/api/v0/item/4fe672886ec142f6ab6d72d54acf046f/"
-F "file=#back_cover.png"
Here's my code:
MultiValueMap<String, Object> params= new LinkedMultiValueMap<>();
params.add("item", "/api/v0/item/4fe672886ec142f6ab6d72d54acf046f/");
final String filename=file.getOriginalFilename();
Resource contentsAsResource = new ByteArrayResource(file.getBytes()){
#Override
public String getFilename(){
return filename;
}
};
HttpHeaders imageHeaders = new HttpHeaders();
imageHeaders.setContentType(MediaType.IMAGE_PNG);
HttpEntity<Resource> imageEntity = new HttpEntity<Resource>(contentsAsResource, imageHeaders);
params.add("file", imageEntity);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.ALL));
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String,Object>> requestEntity =new HttpEntity<>(params,headers);
try {
ResponseEntity<String> responseEntity = restTemplate.exchange(url,HttpMethod.POST, requestEntity, String.class);
return responseEntity.getBody();
} catch (final HttpClientErrorException httpClientErrorException) {
return httpClientErrorException.getResponseBodyAsString();
} catch (Exception exception) {
return exception.getMessage();
}
The above request throws a HttpClientErrorException and this what the response body looks like
{"error": {"message": "Expected multipart/form-data; boundary=<..> content but got multipart/form-data;boundary=x6G0xWVxdZX4n8pYNU8ihGAnCg4Twj3DgMARYDs.", "code": "WRONG_CONTENT_TYPE"}}
I have also tried using FileSystemResource, but it throws the same exception. The problem probably lies in formatting the data in multipart content-type.
If it can help, this is the code template generated by Postman on a successful request using Okhttp.
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
RequestBody body = RequestBody.create(mediaType,
"------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n
Content-Disposition: form-data; name=\"item\"\r\n\r\n/api/v0/item/3d8dcdd1daa54bcfafd8d1c6a58249b5/\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n
Content-Disposition: form-data; name=\"file\"; filename=\"times_logo.png\"\r\nContent-Type: image/png\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");
Request request = new Request.Builder()
.url("https://my.craftar.net/api/v0/image/?api_key=c6d4750c7368806fab27294fba8d0f93d48e1e11")
.post(body)
.addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
.addHeader("cache-control", "no-cache")
.addHeader("Postman-Token", "cf09a989-338e-4d68-8968-b30a43384e5f")
.build();
Response response = client.newCall(request).execute();
just add the Resource to params instead of creating a HttpEntity
params.add("file", contentsAsResource);