7

I have a post request where i need to send x-www-form-urlencoded keyValue pair parameters and content-type should be x-www-form-urlencoded.

Before coding ,i've tried in postman successfully,just adding Header"Content-Type=application/x-www-form-urlencoded" with x-www-form-urlencoded body .

Here is my code:`

 RestAssured.baseURI="****"
        RequestSpecification request = RestAssured.given().config(RestAssured.config()
                .encoderConfig(EncoderConfig.encoderConfig()
                .encodeContentTypeAs("x-www-form-urlencoded",
                 ContentType.URLENC)))
                .contentType(ContentType.URLENC.withCharset("UTF-8"))
                .formParam("grant_type", *)
                .formParam("code", *)
                .formParam("client_id",*)
                .when().log().all()
                .then().log().all().request()
        request.post("/oauth2/token")`

I guess rest assured posted as formParam not "x-www-form-urlencoded"? This is rest assured log: `

Request method: POST
Request URI:    ***
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    grant_type=***
                code=***
                client_id=***
Path params:    <none>
Headers:        Accept=image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap
                Content-Type=application/x-www-form-urlencoded; charset=UTF-8
Cookies:        <none>
Multiparts:     <none>
Body:           <none>
HTTP/1.1 405 Method Not Allowed
Content-Length: 61
Date: Tue, 30 Jan 2018 06:59:20 GMT
X-Correlationid: 5d155b6f-0d85-4775-5f50-82c397e5b44b
X-Smp-Log-Correlation-Id: 5d155b6f-0d85-4775-5f50-82c397e5b44b
X-Vcap-Request-Id: 5d155b6f-0d85-4775-5f50-82c397e5b44b
Only support Content-Type:application/x-www-form-urlencoded

` This problem drives me crazy for a couple f days . Please do let me know is there any other way to send x-www-form-urlencoded parameters or some updation required in code.

Thanks a lot!

Williams
  • 71
  • 1
  • 1
  • 3

5 Answers5

14
Response response = RestAssured
    .given()
    .contentType("application/x-www-form-urlencoded; charset=utf-8")
        .formParam("grant_type", "password")
        .formParam("username", user_email)
        .formParam("password", user_password)
        .formParam("audience", audience)
        .formParam("scope", "openid email")
        .formParam("client_id", REGULAR_APP_CLIENT_ID)
        .formParam("client_secret", REGULAR_APP_SECRET_ID)
    .when()
        .post(AUTH0_URL);
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Dmytro Faliush
  • 151
  • 1
  • 5
4

If you need send request with params in body:

String body = String.format("grant_type=%s&code=%s&clientid=%s", grantType, code, clientId);
Response response = given().with().
header("Content-Type", "application/x-www-form-urlencoded").
body(body).
post("/oauth2/token");

Case for params in URL:

Response response = given().with().
header("Content-Type", "application/x-www-form-urlencoded").
post("/oauth2/token?grant_type={type}&code={code}&clientid={id}");

Case for params in header (also might use Header object io.restassured.http.Header):

Response response = given().with().
header("Content-Type", "application/x-www-form-urlencoded").
header("grant_type", type).
header("code", code).
header("clientid", id).
post("/oauth2/token");

BTW use static give() for don't duplicate Config

public static RequestSpecification given() {
RestAssured.config = RestAssured.config().
...;
return given().baseUrl(BASE_URL).contentType(ContentType.URLENC);
}
  • Well I've tried as your suggestion ,but it doesn't work with response code 405.By the way my rest assured version is 3.0.3.I find the type "ContentType.URLENC" only without " ContentType.APPLICATION_FORM_URLENCODED".It seems that put msg in body is not right solution. However i use the java.net.HttpURLConnection to post urlencoded getting the right answer. – Williams Feb 02 '18 at 01:30
  • @Williams Are you sure about request method is correct? May be you have to use get instead? Anyway i have edited my answer for few cases. – Roman Davydov Feb 03 '18 at 07:11
2

This Method is working for me

public String getAuthForKeyCloak() {

    Response response = RestAssured.given().with().auth().preemptive()
            .basic(props.get("keycloak_username"), props.get("keycloak_password"))
            .header("Content-Type", "application/x-www-form-urlencoded")
            .formParam("grant_type", props.get("keycloak_granttype"))
            .formParam("client_id", props.get("keycloak_clientid"))
            .formParam("username", props.get("keycloak_username"))
            .formParam("password", props.get("keycloak_password")).when()
            .post(ApplnURIForKeyCloak + props.get("keycloakAuthURL"));

    System.out.println(response.getBody().asString());

    String responseBody = response.getBody().asString();
    String token = new org.json.JSONObject(responseBody).getString("access_token");
    System.out.println(token);
    return token;
    }
rammelmueller
  • 1,092
  • 1
  • 14
  • 29
Sohan
  • 21
  • 2
0

Use RA EncoderConfig to encode the content type for content-type x-www-form-urlencoded. Also, post the payload as form parameters

RequestSpecBuilder.setConfig(RestAssured.config().sslConfig(SSLConfig.sslConfig().relaxedHTTPSValidation())
                .encoderConfig(EncoderConfig.encoderConfig()
                        .encodeContentTypeAs("x-www-form-urlencoded",
                                ContentType.URLENC)))
                .setContentType("application/x-www-form-urlencoded; charset=UTF-8");
bodhi
  • 203
  • 3
  • 14
-1

I had the same issue and I finally found the solution:

Understanding the issue: Rest Assured automatically concatenates a charset after the content type, even if you do not specify one.

i.e if you set the Content-Type to be application/x-www-form-urlencoded it will automatically set a default charset to it and your log will display:

Content-Type=application/x-www-form-urlencoded; charset=ISO-8859-1 or some other charset.

My problem was that I needed the content type to be without any charset, otherwise it was not accepted and returned status code 400.

The solution is to make sure you send the content type WITHOUT ANY charset.

How to use: Before you set the content type, add this line:

RequestSpecification rs= RestAssured.given();

rs.config(RestAssured.config().encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false)));

this part : 
appendDefaultContentCharsetToContentTypeIfUndefined(false)))

will make sure that no charset will be appended to your content type.

Then set the header:

rs.header("Content-Type", "application/x-www-form-urlencoded");
abhinavsinghvirsen
  • 1,853
  • 16
  • 25
  • This was the exact issue I was facing. Cloudfront was blocking my requests (returning a 403) but as soon as I removed the `charset` as described, it allowed the request through. – markblandford Apr 19 '23 at 16:36