How do we pass multiple headers in rest assured? - http-headers

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

Related

HttpClient default headers not working with Microsoft.Owin.Testing.TestServer

I'm using the Microsoft.Owin.Testing library to integration test my API in-memory. I've added in the OWIN JWT middleware for my authentication needs, and am now trying to pass a generated token to test requests to controllers needing authorization. I can assure you that the JWT middleware is setup correctly, as it works just fine with normal use. However, I am observing some strange behavior with the TestServer.HttpClient object. When I set a default authorization header on HttpClient to pass the token, my tests never pass because the token is not recognized. However, when I use TestServer.CreateRequest(...), the test passes correctly and the token is recognized. I would prefer to use the HttpClient methods because they make things a hell of a lot easier with all the extension methods provided such as PostAsJsonAsync, etc. I'm beginning to think there is either a bug in the TestServer.HttpClient or I that am completely missing something.
Here's my test class (using NUnit3):
public class DefinitionsControllerTests
{
private TestServer _server;
private string _accessToken;
[SetUp]
public void Setup()
{
_server = TestServer.Create<Startup>();
var credentials = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", "john.doe#mail.com"),
new KeyValuePair<string, string>("password", "testing123")
});
// get token from OWIN JWT middleware
dynamic resultBody = JObject.Parse(
_server.HttpClient.PostAsync("/oauth/token", credentials).Result.Content.ReadAsStringAsync().Result);
_accessToken = (string)resultBody.access_token;
// this does not appear to ever work
_server.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
}
[TearDown]
public void TearDown()
{
_server.Dispose();
}
[Test]
public void GetById_WithExistingId()
{
// 401 Unauthorized response everytime and test fails
var response = _server.HttpClient.GetAsync($"/api/definitions/{expected.Id}").Result;
var actual = response.Content.ReadAsAsync<Definition>().Result;
// 200 Ok every time and test passes
// - these variables aren't part of the test but rather to show alternate request creation method that works
var response2 = _server.CreateRequest($"/api/definitions/{expected.Id}")
.AddHeader("Authorization", "Bearer " + _accessToken)
.GetAsync()
.Result;
var actual2 = response.Content.ReadAsAsync<Definition>().Result;
response.StatusCode.ShouldBe(HttpStatusCode.OK);
actual.ShouldNotBeNull();
}
//...other test methods
}
And my controller:
[Authorize]
public class DefinitionsController : ApiController
{
private readonly IDefinitionRepository _repo;
public DefinitionsController(IDefinitionRepository repo)
{
_repo = repo;
}
public IHttpActionResult Get(Guid id)
{
var definition = _repo.Get(id);
if (definition == null)
return NotFound();
return Ok(definition);
}
}
Anyone have any idea why only CreateRequest() works? This is slightly infuriating.
The problem is that the HttpClient property returns a new instance every time. It will work if you save that instance and re-use it.
https://github.com/aspnet/AspNetKatana/blob/b850cd8b4de61e65bbd7127ce02b5df7c4cb6db5/src/Microsoft.Owin.Testing/TestServer.cs#L48

How to decode JWT (Header and Body) in java using Apache Commons Codec?

I am looking decode the following JWT using Apache Commons Codec. How we can do that ?
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0Iiwicm9sZXMiOiJST0xFX0FETUlOIiwiaXNzIjoibXlzZ
WxmIiwiZXhwIjoxNDcxMDg2MzgxfQ.1EI2haSz9aMsHjFUXNVz2Z4mtC0nMdZo6bo3-x-aRpw
This should retrieve Header, Body and Signature part. Whats the code ?
Here you go:
import org.apache.commons.codec.binary.Base64;
#Test
public void testDecodeJWT(){
String jwtToken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0Iiwicm9sZXMiOiJST0xFX0FETUlOIiwiaXNzIjoibXlzZWxmIiwiZXhwIjoxNDcxMDg2MzgxfQ.1EI2haSz9aMsHjFUXNVz2Z4mtC0nMdZo6bo3-x-aRpw";
System.out.println("------------ Decode JWT ------------");
String[] split_string = jwtToken.split("\\.");
String base64EncodedHeader = split_string[0];
String base64EncodedBody = split_string[1];
String base64EncodedSignature = split_string[2];
System.out.println("~~~~~~~~~ JWT Header ~~~~~~~");
Base64 base64Url = new Base64(true);
String header = new String(base64Url.decode(base64EncodedHeader));
System.out.println("JWT Header : " + header);
System.out.println("~~~~~~~~~ JWT Body ~~~~~~~");
String body = new String(base64Url.decode(base64EncodedBody));
System.out.println("JWT Body : "+body);
}
The output below:
------------ Decode JWT ------------
~~~~~~~~~ JWT Header ~~~~~~~
JWT Header : {"alg":"HS256"}
~~~~~~~~~ JWT Body ~~~~~~~
JWT Body : {"sub":"test","roles":"ROLE_ADMIN","iss":"myself","exp":1471086381}
Here is a non-package-import way:
java.util.Base64.Decoder decoder = java.util.Base64.getUrlDecoder();
String[] parts = jwtToken.split("\\."); // split out the "parts" (header, payload and signature)
String headerJson = new String(decoder.decode(parts[0]));
String payloadJson = new String(decoder.decode(parts[1]));
//String signatureJson = new String(decoder.decode(parts[2]));
REGARDLESS (of this alternative to org.apache.commons.codec.binary.Base64 SiKing'sanswer )... you may want to also push those json fragments to pojo's.
You can then take those json fragments and turn them into pojo.
The headers are "dynamic" (as in, you don't know all the header-names beforehand), so you probably want to convert to Key Value pairs (aka "Map" in java)
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class JwtTokenHeaders {
private final Map<String, Object> jsonMap; // = new HashMap<String, Object>();
public JwtTokenHeaders(String jsonString) {
ObjectMapper mapper = new ObjectMapper();
//String jsonString = "{\"name\":\"JavaInterviewPoint\", \"department\":\"blogging\"}";
//Map<String, Object> jsonMap = new HashMap<String, Object>();
try {
// convert JSON string to Map
this.jsonMap = mapper.readValue(jsonString,
new TypeReference<Map<String, String>>() {
});
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
#Override
public String toString() {
return org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(this);
}
}
the payload (aka, the body) is more well-defined, so you can map to a pojo..... you can take the json and create a matching pojo here:
http://pojo.sodhanalibrary.com/
after you use an online tool (or hand craft the pojo youself)..to create something like "MyPojo(.java)"....
you'll end up with something like this:
//import com.fasterxml.jackson.databind.DeserializationFeature;
//import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyPojo tp = mapper.readValue(payloadJson, MyPojo.class);
if http://pojo.sodhanalibrary.com/ ceases to exist in the future, just internet search "online json to pojo" and you'll probably find something.

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.

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

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.