How to construct message header for a HEAD response with restlet - 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.

Related

Reverse Proxy with Asp.Net Core

I have written a middleware that catches the request and based on the requirement it sends HttpRequest (with the help of HttpClient) and copies all the HTTP response parts(headers, body) from the result to my context. But when I get
transfer-encoding: chunked
in the header, the response is not returning to the end-user properly.
How can I copy the exact same response to my context and continue correctly?
private void CopyFromTargetResponseHeaders(HttpContext context, HttpResponseMessage responseMessage)
{
foreach (var header in responseMessage.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
foreach (var header in responseMessage.Content.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
}

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

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.

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();

Logging the XML or JSON sent by RestSharp

I'm using RestSharp to send information to a API. I would like to log the XML that I've sent to this API so I can debug later.
I would like to do something like this:
var request = new RestRequest(resourcePath, method);
request.AddBody(dto);
Logger.Log(request.Content);
var response = Client.Execute(request);
But, the actual request sent by RestSharp does not seem to be exposed.
Everything sent in the request is available in request.Parameters.
To make getting the request body easier I created this extension method:
public static class RestSharpExtensions
{
public static string GetBody(this IRestRequest request)
{
var bodyParameter = request.Parameters
.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
return bodyParameter == null
? null
: bodyParameter.Value.ToString();
}
}

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 .