5

The below sample code is in http client , But I want to write the same in Rest Assured. I know we can use the http lib in rest assured as well, But I want to have in Rest assured

HttpPost pst = new HttpPost(baseUrl, "j_spring_security_check"))
pst.setHeader("Content-Type", "application/x-www-form-urlencoded")
ArrayList<NameValuePair> postParam = new ArrayList<NameValuePair>()
postParam .add(new BasicNameValuePair("j_username",username))
postParam .add(new BasicNameValuePair("j_password",password))
UrlEncodedFormEntity formEntity23 = new UrlEncodedFormEntity(postParam)
pst.setEntity(formEntity23 )
HttpResponse response = httpclient.execute(pst);

2 Answers2

10

For Rest Assured you can use below code snippet.

Response response = RestAssured
    .given()
    .header("Content-Type", "application/x-www-form-urlencoded")
    .formParam("j_username", "uName")
    .formParam("j_password", "pwd")
    .request()
    .post(url);

As, your application is using form url-encoded content type you can set the Header type to this as mentioned above.

Hope, this helps you.

ESV
  • 7,620
  • 4
  • 39
  • 29
Srikanth Gupta
  • 116
  • 1
  • 3
1
@Test
public void postRequestWithPayload_asFormData() {
    given().contentType(ContentType.URLENC.withCharset("UTF-8")).formParam("foo1", "bar1").formParam("foo2", "bar2").log().all()
            .post("https://postman-echo.com/post").then().log().all().statusCode(200)
            .body("form.foo1", equalTo("bar1"));
}

Add content type of URLENC with charaset as UTF-8. It works will latest rest assured.

Vishwak
  • 158
  • 9