com.jayway.restassured.RestAssured Getting Response code : 400 for PUT Request - api

import static com.jayway.restassured.RestAssured.given;
import com.jayway.restassured.builder.RequestSpecBuilder;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.RequestSpecification;
public class PUTAPI {
public void addNewObject() throws Throwable {
//Creating api body
String xmlBody ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+"<PlanRunRequest>"
+"<PlannedRunName>LIMS_Plan_Run_001</PlannedRunName>"
+"<Assay></Assay>"
+"<ReportingTemplate>LIMS_Report1</ReportingTemplate>"
+"<TubeLabel>tube2343</TubeLabel>"
+"<TemplateKitBarcode>91A18930101212-1234567171603172100001301</TemplateKitBarcode>"
+"<PlanRunNotes>This is my 1st Plan</PlanRunNotes>"
+"<LibraryPrepIDs>"
+"<LibraryPrepID specimenID=\"\">1004</LibraryPrepID>"
+"</LibraryPrepIDs>"
+"</PlanRunRequest>";
System.out.println(xmlBody);
//Specifying request body details
RequestSpecBuilder builder = new RequestSpecBuilder().setContentType("application/xml");
RequestSpecification requestSpec = builder.build();
requestSpec.baseUri("http://10.88.195.88").basePath("/ir/lims/create-library-batch").contentType("application/xml");
//Making post request with authentication
Response response =given().body(xmlBody).header("username","Auto1Admin").header("password", "ion123").spec(requestSpec).when().put();
System.out.println("ir"+response.body().asString());
System.out.println(response.getStatusCode() );
}
public static void main (String [] args) throws Throwable {
PUTAPI service = new PUTAPI();
service.addNewObject();
}
}
Verified 'String xmlBody' i.e. XML request body with XML-validator, No error found. Verified the request URI, body and headers by submitting this query through postman. It shows me success response code 200 k, But when i run the above script which has correct URI, body and headers its showing response code 400 - bad request.Please help me sort out this issue.

Related

How can let my filter let the reactive request to pass and not block them

In my architecture, i have some custom starter that centralize all the dependencies and the methods that are common for my microservices, in one of those starter i have a method that play the role of a filter of all the request of my projet in all the microservices,the problem is that this filter don't let the reactive request written in webflux to pass, when i test in postman or in a front web app i get a 200 OK response but an empty payload and empty json. I which to know if there is any way to allow my reactive request to pass without being blocked.
There is my filter method:
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(
(HttpServletRequest) servletRequest);
MDC.clear();
String uniqueId = String.valueOf(Instant.now().toEpochMilli());
MDC.put("traceId", uniqueId);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(
(HttpServletResponse) servletResponse);
log.info("Request path {}, {}, Address {}", requestWrapper.getRequestURI(), requestWrapper.getMethod(),
servletRequest.getRemoteAddr());
filterChain.doFilter(servletRequest, responseWrapper);
responseWrapper.setHeader("traceId", uniqueId);
responseWrapper.copyBodyToResponse();
MDC.put("status", String.valueOf(responseWrapper.getStatus()));
log.info("Response path {} status {}", requestWrapper.getRequestURI(),
String.valueOf(responseWrapper.getStatus()));
MDC.clear();
}
and there is an example of one of my reactive methods:
#GetMapping("/{id}")
public Mono<ResponseEntity<List<ResponseDTO>>> retrieve(#PathVariable("id") String id) {
return reactor.core.publisher.Mono.fromCallable(() -> new ResponseEntity<>(
this.service.retrieveById(id), org.springframework.http.HttpStatus.OK)::get).subscriberContext( ReactiveSecurityContextHolder.withSecurityContext(reactor.core.publisher.Mono.just(SecurityContextHolder.getContext())));
}
Dispose d’un menu contextuel

OkHttp Post Body as JSON is throwing 404

I recently moved into OKHTTP. I'm able to perform get request but while performing post i'm getting 404. Can someone help me out where I'm going wrong.
FYI:
auth token is correct & url is valid
public void PullRequest() throws IOException{
JSONObject jo = new JSONObject();
jo.put("head","patch-7");
jo.put("base","main");
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jo.toString());
//RequestBody body = RequestBody.create(jo.toString(),JSON);
Request request = new Request.Builder()
.url(url)
.header("Authorization",authorization)
.post(body)
.build();
Call call = httpClient.newCall(request);
Response response = call.execute();
if (response.code()>300) {
System.out.println("error...");
System.out.println(response.body().string());
}else {
System.out.println(response.body().string());
}
}

How do we pass multiple headers in rest assured?

I am new to rest-assured and Java, I am trying to do a very basic test of checking the response is 200 ok for API.
can you any one please tell me what do I need to change in the below script in order to pass multiple headers Id, Key and ConId?
import org.junit.Test;
import com.jayway.restassured.*;
import com.jayway.restassured.http.ContentType;
import static org.hamcrest.Matchers.*;
import static com.jayway.restassured.RestAssured.*;
public class APIresponse
{
public static void main(String[] args)
{
APIresponse apiresponse = new APIresponse();
apiresponse.response();
}
#Test
public void response ()
{
baseURI="http://testme/api/";
given().
header("Id", "abc").
param("Key", "NuDVhdsfYmNkDLOZQ").
param("ConId", "xyz").
when().
get("/uk?Id=DT44FR100731").
then().
contentType(ContentType.JSON).
body("response.code", equalTo("200"));
}
}
Simplest way to add multiple headers is to just repeat .header(headername,headervalue) multiple times after .given()
given().
header("Id", "abc").
header("name","name").
header("","")
...
You can find different ways of passing headers using REST-Assured framework in its test suite at this github link.
Edit:
To verify response status in Rest-Assured:
expect().statusCode(200),log().ifError().given()......
or pick an example of how you want to test response header from this github link
you can also create and add Map Object of multiple headers as below
Header h1= new Header("Accept", "*/*");
Header h2 = new Header("Accept-Language", "en-US");
Header h3 = new Header("User-Agent", "Mozilla/5.0");
List<Header> list = new ArrayList<Header>();
list.add(h1);
list.add(h2);
list.add(h3);
Headers header = new Headers(list);
request.headers(header);
Or you can use Headers() from RestAssured which support you to add multiple headers at the same time to request.
Headers description
Replace like below:
#Test
public void response ()
{
baseURI="http://testme/api";
given()
.header("Id", "abc")
.param("Key", "NuDVhdsfYmNkDLOZQ")
.param("ConId", "xyz")
when()
.get("/uk?Id=DT44FR100731")
then()
.contentType(ContentType.JSON)
.and()
.body("response.code", equalTo("200"));
}
This is how I used with RequestSpecification and I added two headers.
#Test
public void PostRequest() {
String appKey = "777";// userID is unique
RequestSpecification myreq = RestAssured.given();
myreq.header("Content-Type", "application/json");
myreq.header("Authorization", "Bearer 777");
// Create Json Object to store attributes
JSONObject myjson = new JSONObject();
myjson.put("app_key", appKey);
myjson.put("status", "critical")
// Attach those attributes to Body after convert them in to JsonString
myreq.body(myjson.toString());
// Post the request with URL
Response MyRes = myreq.post("https://api.bigpanda.io/data/v2/alerts");
int ActualStatuscode = MyRes.getStatusCode();
}
this might help:
Map<String,Object> headerMap = new HashMap<String,Object>();
headerMap.put("first_name", "John");
headerMap.put("last_name", "Watson");
Response response = given()
.baseUri("http://localhost")
.basePath("user/details")
.headers(headerMap)
.get();

Dropwizard / JerseyClient ignored JsonProperty when sending http request

I have two REST services implemented with Dropwizard-0.8.
Both share an API dependency with following POJO:
public class Report{
private String text;
#JsonProperty("t")
public String getText()
{
return text;
}
public void setText(String tx)
{
text = tx;
}
}
My Server has a rest recourse:
#POST
#Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8")
#Produces(MediaType.TEXT_PLAIN + ";charset=UTF-8")
#Timed
public Response receive(Report dto) {
//do some stuff with dto
}
My Client has a method :
sendReport(report);
with:
private void sendReport(Report report) {
final String uri = "http://localhost:8080/.....";
Response response = null;
try {
response = client.target(uri).request().post(Entity.entity(report, MediaType.APPLICATION_JSON), Response.class);
final int status = response.getStatus();
if (status != Status.ACCEPTED.getStatusCode()) {
final StatusType statusInfo = response.getStatusInfo();
throw new SomeException();
}
}
catch (Exception e) {
LOGGER.error(e.getMessage());
}
finally {
if (response != null) {
response.close();
}
}
}
The Client is made in the Dropwizard application class with:
service.client = new JerseyClientBuilder(env).using(conf.getJerseyClient()).withProvider(JacksonJaxbJsonProvider.class).build(getName());
env.jersey().register(service);
Where 'service' is my rest class calling the 'sendReport' method.
Problem
When I call the rest service of my server from a browser or with curl etc it works perfectly as expected with following messagebody:
{"t":"some text for the server"}
But when I run my application to call the rest service I get a 400 "unable to process JSON".
Debugging and the log messages showed me that the application sends the following JSON to my server:
{"text":"some text for the server"}
Which leads to the error that Jackson cant find a property "text".
Why is the JerseyClient ignoring the JsonProperty annotation?
From what I understand you using Entity.entity from jersey which has no idea about the #JsonProperty annotation(which is from jackson library) . What you need to do is do serialisation using a jackson library and give it to post call .

How to construct message header for a HEAD response with restlet

I'm trying to create a HEAD response with restlet. Unfortunatly there is ony a #Get annotation, but the restlet author states, that you have to use a #Get, and then compare the Method.
As the documentation/specification says, there can be no body, but only a message header.
Now how to create a message header that will be send to the server, because the following code does not work, it sends this headers: HTTP/1.1 204 No Content, Content-Length: 0
protected void addResponseHeader(String name, String value) {
Form responseHeaders = (Form)getResponse().getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
if (responseHeaders == null) {
responseHeaders = new Form();
getResponse().getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders);
}
responseHeaders.add(new Parameter(name, value));
}
The concrete code on server-side:
#Get
public void execute() {
if (Method.HEAD.equals(getMethod())) {
//optional: getResponse().getEntity().setMediaType(MediaType.TEXT_PLAIN);
getResponse().setStatus(Status.SUCCESS_OK, "hello head");
addResponseHeader("X-my-header", "value");
}
}
The client code:
#Test
public void head() {
Request request = new Request(Method.HEAD, url);
Response response = query(request);
assertEquals(Status.SUCCESS_OK, response.getStatus());
Form form = (Form)response.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
assertEquals("value", form.getFirstValue("X-my-value")); // does fail because it is null
}
You just need to implement #Get for real : should work with a HTTP GET fine first. Then if you issue a HTTP HEAD, it will be handled automatically by the framework, nothing else to do on your side. Just focus on getting GET implemented correctly.