I have a POST request, which I tried first in Postman, I wanted to capture the status code before it's redirected. In Postman, I got 307 (I set the settings so it doesn't follow redirects).
Postman
But when I tried using restassured, it still got redirected, so I got 200 status code instead of 307.
Tried the same way with GET request with 302 status code, and that one works.
public void postDataBeforeLogin() {
//post data before login
Response response = RestAssured.given().redirects().follow(false).post("/data");
assertEquals(response.getStatusCode(), 307);
}
I read an article/post about restassured not redirecting POST requests, but it was from 3 years ago, so I'm not sure if that is still the case.
Can anyone help/clarify?
Help will be greatly appreciated, thank you!
RestAssuredConfig will meet your requirements, like this:
given().config(RestAssured.config().redirect(redirectConfig().followRedirects(false))).
in your case:
import static io.restassured.config.RedirectConfig.redirectConfig;
Response response = RestAssured.given()
.config(RestAssured.config().redirect(redirectConfig().followRedirects(false)))
.post("/data");
See more: REST-assured wiki
It's recommended to statically import methods, see this
Related
I want to change data on a server via a put request, but I always get a 401 [no body] error. The response looks like the following:
I do not really understand why I get this error, because my body is not empty. My code looks like this and the values seem to be okay too. Does anyone have any idea what I'm doing wrong?
Postman Update:
The values are different right now (consent and authorisation) since its basically a new request but the values were correct before too so this change should not make a difference.
Looks like you are simply passing invalid authorization header, or maybe not passing it at all.
What happens is that you make a RestTemplate exchange call, then you get 401 from that request, and Spring propagates it and returns 500 - Internal Server Error, because there is no error handling in place.
EDIT: According to your screenshots, you are not replacing your path variables. Update the way you build your URL as listed below.
Map<String, String> pathVars = new HashMap<>(2);
pathVars.put("consent-id", consentId);
pathVars.put("authorisation-id", authorisationId);
UriComponents uri = UriComponentsBuilder.fromUri(mainLink)
.path("consents/{consent-id}/authorizations/{authorisation-id}")
.buildAndExpand(pathVars);
Verify if your authorization-id is correct
if the token has a type for example Bearer you must write so:
"Authorization": "Bearer rrdedzfdgf........."
and make sure that there is only one space between Bearer and the token
Often the problem comes from the browser locally;
if your site is online, save the part and deploy the last modifications of the site and make the test
otherwise if it is a mobile application test it on a smartphone and not a browser;
in case none of this works, do it with your backend, it works with this
I had a problem where the I would add an extra character to a password. And Insomnia(Or Postman) would return a JSON response from the server along with a 401 HTTP status code. But when I did the same thing inside a springboot app, when using catch(HttpServerErrorException e){System.out.prinln(e.getMessage());} the e.getMessage would have [no body]. I think that is a feature built in the HttpServerErrorException class where it doesn't provide the body for security purposes. Since whoever is requesting is not authorized they should not have access to it.
I have a HTTP GET which returns status 200 with some response. This response it is given as a result of redirecting.
If I introduce asyncHttpClient.setEnableRedirects(false); in my code, then redirection stops and it comes in failure with status 302. But in my application, this status 302 and response associated with it is what I need.
I am searching online and trying to figure out, but I am new to Java so not able to understand how to achieve this.
What I want is, when server returns status 302, I want to trigger onSuccess and capture response. Thanks.
If I'm getting right what do you need then you could implement your own AsyncHandlers to react with a different AsyncHandler.State for 302 status code. ( https://github.com/AsyncHttpClient/async-http-client#using-custom-asynchandlers) or while creating the client stop to follow redirects like this:
asyncHttpClient(config().setFollowRedirect(false))
(it might be different from the approach you mentioned above.)
P.S. I'm using 2.5.2 version of the asynchttpclient lib.
fellow stackoverflowians :)
I've been for quit time to make a Post call using Gmail API.
Been trying to use createDraft and createLabel.
Now I guess I've found how to do this correctly (mostly) but I get this error:
java.lang.AssertionError: 1 expectation failed.
Expected status code <200> but was <400>.
I realise that this error occurs because I make incorrect request.
Could You, guys, help me with this?
Here's my code:
import io.restassured.RestAssured.*
import io.restassured.http.ContentType
import io.restassured.matcher.RestAssuredMatchers.*
import org.hamcrest.Matchers.*
import org.testng.annotations.Test
class RestAPIAutoTestPost {
#Test
fun createLabelInGoogleMail() {
RestAssured.baseURI = "https://www.googleapis.com/gmail/v1/users/me"
val accessToken = "ya29.Glw7BEv6***"
val jsonAsMap = HashMap<String, Any>()
jsonAsMap.put("id", "labelAPITestNameID")
jsonAsMap.put("labelListVisibility", "labelShow")
jsonAsMap.put("messageListVisibility", "show")
jsonAsMap.put("messagesTotal", "0")
jsonAsMap.put("messagesUnread", "0")
jsonAsMap.put("name", "labelAPITestName")
jsonAsMap.put("threadsTotal", "0")
jsonAsMap.put("threadsUnread", "0")
jsonAsMap.put("type", "user")
given().
contentType(ContentType.JSON).
body(jsonAsMap).
`when`()
post("/labels?access_token=$accessToken").
then().
statusCode(200)
}
}
I suppose I use HashMap incorrectly or I use some incorrect body fields.
I've only started to learn restAssured so I beg my pardons for newby question.
Thanks!
P.S. I'd really appreciate for any help with Post methods and puting data into body
I think your use of RestAssured and HashMap is correct. I think you are getting a 400 from this API because you are specifying the id property. By playing with this in Google's API Explorer, I was able to generate 400 errors by doing that. According to the documentation, the only things you need to specify for a POST/Create are: labelListVisibility, messageListVisibility, and name. The id is returned to you as part of the response.
A good feature in RestAssured is that you can have it log what it sends or receives when there is an error or all the time.
Log all requests:
given().log().all()
Log all responses:
`when`().log().all()
Or just when validations fail:
`when`().log().ifValidationFails()
Using that will give you a more precise reason why your interaction with the API is failing because it will show whatever Google is sending back. So we can see for sure if I'm right about the id.
And since you seem to be using Kotlin for this, you might want to take advantage of its great multiline string capabilities and just create the JSON payload manually:
val body = """
{
"labelListVisibility": "labelShow",
"messageListVisibility": "show",
"name": "ThisIsATest"
}
"""
I'm trying to make a request to the Genius API, but I'm running into some issues using OkHTTP. This is my small script I'm using to make the call:
public class OkHttpScript {
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.header("Authorization", "Bearer uDtfeAgTKL3_YnOxco4NV6B-WVZAIGyuzgH6Yp07FiV9K9ZRFOAa3r3YoxHVG1Gg")
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static void main(String[] args) throws IOException {
OkHttpScript okHttpScript = new OkHttpScript();
String response = okHttpScript.run("http://api.genius.com/songs/378195/");
System.out.println(response);
}
}
When I run this script, I get a 403 error:
{"meta":{"status":401,"message":"This call requires an access_token. Please see: https://genius.com/developers"}}
For reference, here is a picture of me making the same exact request with Postman, and it works:
Any ideas on what the problem could be?
Edit:
Not sure if this is normal, but when I print out my request object that gets built, I see no indication that there are headers in the request:
Request{method=GET, url=http://api.genius.com/songs/378195/, tag=null}
Is what I get. Could this be part of the problem?
Edit2:
Nevermind, doing a
System.out.println(newRequest.headers());
gives me what I originally put in:
Authorization: Bearer 4mfDBVzCnp2S1Fc0l0K0cfqOrQYjRrb-OHi8W1f-PPU7LNLI6-cXY2E727-1gHYR
So I figured out what my problem was. I'm not sure of the details behind it, but I should have been using my URL has https://api.genius.com/songs/378195/ instead of http://api.genius.com/songs/378195/
Postman seems fine with the http, but OkHttp needed https.
Not sure how your server side is written, I had the same problem today when requesting someone else's service. My solution was to change the User-Agent, even if PostmanRuntime/7.26.10
You should add an interceptor for okhttp something like this should work
How to handle auth0 403 error without adding specific code everywhere (Retrofit/okhttp/RxAndroid)
*Used Alex Hermstad Answer
--> Use https instead of http in android ,
Postman seems fine with the http, but OkHttp needed https.
I was stuck for a day for this error 403 forbidden in android , but giving 200 success in Postman .
I am working on a Javascript snippet that communicates with a local Java Server with the help of HTTP Requests.
My requests looks like this:
var req = $.ajax({
type : "GET",
dataType : "json",
url : "http://127.0.0.1:8081",
data : data_dict
});
The response header, that I send from my Java Server, seems to be okay (at least the Firefox Web Developer tells me so). But there is an error on body parsing:
JSON.parse: unexpected end of data at line 1 column 1 of the json data
Seems like my response is empty... but when I open
http://127.0.0.1:8081/?test_request_key=test_request_value it shows the expected body in my browser:
{"test_respond_key":"test_respond_val"}
Do you have a hint for me? I have no idea where to search for the problem...
EDIT: The complete Response is
HTTP/1.1 200 OK
Server: Java HTTPStudyServer
Content-Type: application/json
Content-Length: 39
Connection: close
{"test_respond_key":"test_respond_val"}
Thanks in advance!
(and sorry if this is a noob problem with a simple answer, but some hours of googling didn't help me out)
Okay, I found the solution (with your help!)
The problem was indeed CORS! If you look at the examples at http://de.wikipedia.org/wiki/Same-Origin-Policy you see that for another port it does not count as same origin!
This post gave me proof: Why is same origin policy kicking in when making request from localhost to localhost?
So I simply added this line to the Response Header:
Access-Control-Allow-Origin: *
Now it works like a charm! :)
Thank you for your help guys!
Greetings