No Response when Restassured url has custom encoding - rest-assured

I am using rest-assured to test REST APIs, when hitting the url, url has it own encoded parameters.
Response b = given().
relaxedHTTPSValidation().body(gbody).
with().
contentType(ConfigReader.get("application.json")).
then()
.post(url);
It ran successfully but response is empty.
Please tell what can be the reason

This is because, rest-assured will automatically encode the url when you are encoding the url, you need to use method urlEncodingEnabled(false), so that , it will not encode the url again.
Now your code will become
Response res = given()
.urlEncodingEnabled(false)
.relaxedHTTPSValidation()
.body(gbody)
.with()
.contentType(ConfigReader.get("application.json"))
.then()
.post(url);

Related

Rest Assured basic auth issue

I have an endpoint which works perfectly fine when I use Postman with Basic Auth. However, when I tried it in Rest Assured it returns 401. I have tried both different auth methods in rest assured and none of them worked for me so far. Need help!
RequestSpecification requestSpec;
String baseURI = "http://qa3-phoenix.labcorp.com";
String basePath = "/phx-rest/healthcheck/ping";
RestAssured.useRelaxedHTTPSValidation();
RestAssured.baseURI = baseURI;
requestSpec = new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.build();
Response response = RestAssured
.given()
.spec(requestSpec)
.auth().basic("username","password")
.when()
.get(basePath)
.then()
.extract().response();
One can use directly the Authorization header with base64 encoded username and password and omit the auth() part.
Code example:
String authBasic = Base64.encode(String.format("%s:%s", username, password));
rest()
.header("Authorization", String.format("Basic %s", authBasic))
useRelaxedHTTPSValidation() is a workaround when the server is not using a valid certificate or you bump into SSLPeerUnverifiedException. In most of the scenarios this does not happen.
So try removing useRelaxedHTTPSValidation().
Can you also try the below approach:
While creating your RequestSpecification, can you add an object of authentication scheme to your RequestSpecification and then use that to create http requests.
RequestSpecBuilder req = new RequestSpecBuilder();
PreemptiveBasicAuthScheme auth = new PreemptiveBasicAuthScheme();
auth.setUserName("");
auth.setPassword("");
req.setAuth(auth);
req.build();
May be you can think of creating your RequestSpec from a separate class or package for better re-use.
Let me know if this helps, or the stacktrace.

Post Method with NSDictionary Values using Swift

I'm completely new toSwift. I need to hit a Post Method webservice with NSDictionary parameters & get the JSON response. I tried usingAlamofire & also NSMutableUrlRequest. Nothing seems to workout for me. I either get 'JSON text did not start with array or object and option to allow fragments not set' error or 'Undefined Variable' response from the server. The same service works fine when I try using Objective-C. As I said earlier, I am completely new toSwift & need your assistance.
My base url: http://myofficeit.in/bizfeed/webservices/client.php
Parameter I wanna Pass:
Parameter =
{
UserName = xyz;
deviceModel = iPhone;
deviceToken = "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e";
emailid = "xyz#gmail.com";
location = Asia;
userMobileNo = 1234567890;
};
functionName = register;
The code I used for hitting the service is: http://pastebin.com/aaT4uhS7
Thanks
you can use like
let param: [String:AnyObject] = [
"UserName": iPhone,
"deviceToken": "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e",
"emailid": "xyz#gmail.com",
"location": Asia,
"userMobileNo": 1234567890
]
Alamofire.request(.POST, "http://myofficeit.in/bizfeed/webservices/client.php/register", parameters: param).responseJSON { (req, res, json, error) in
print(req)
print(res)
print(json)
print(error)
}
for sample request in Alamofire
As broad as your question is, the broad will be my answer:
The first thing to do, is to get a clear idea about the web service API, which also requires a basic knowledge of the HTTP protocol. So, what you need to understand is, what the server expects in HTTP terminology.
You eventually will find out, how the server will expect its "parameters". Note, that there is no term like "parameters" in the HTTP protocol. So, you need to map them into something the HTTP protocol provides.
Most likely, in a POST request, "parameters" are transferred as the body of the HTTP message, as a content-type which is application/x-www-form-urlencoded, multipart/form-data or application/json.
According to the needs of the server, and with your basic knowledge of HTTP and NSURLSession, NSURLComponents etc., you compose the URL and the body of the request, set Content-Type header and possibly other headers and you are ready to go.
How this eventually looks like is given in the answer of #AnbyKarthik, which used Alamofire, and a command that composes a POST request whose parameters are send in the body whose content-type is x-www-form-urlencoded.

HttpRequest GET with sendData as query parameters?

This question is kind of a duplicate of HTTPRequest.request with sendData, can't seem to get this to work, but I've got some more information now. The goal here is to send a GET request with query parameters attached. I initially tried to send my request as such:
HttpRequest request = new HttpRequest();
request.open("GET", _url, async:true);
request.onError.listen(_onLoadError, onError: _onLoadError);
request.send(sendData);
Where sendData is a String following the normal format for query parameters (?myVariable=2&myOtherVariable=a, etc), since this is the ultimate goal here. The request gets sent, but I never see any additional data (sendData) go with it in any monitoring tools (I'm using Charles). I then tried:
HttpRequest request = new HttpRequest();
request.open("GET", _url + sendData, async:true);
request.onError.listen(_onLoadError, onError: _onLoadError);
request.send();
So now I'm just attaching the query string to the url itself. This works as intended, but is far from elegant. Is there a better solution?
On a GET request you always add the query string to the URL?
When you create the Uri you can pass in a map with the query parameters if you find this more elegant.
Map query = {'xx':'yy', 'zz' : 'ss'};
String url = "http://localhost:8080/myapp/signinService";
Uri uri = new Uri(path: url, queryParameters : query);
HttpRequest.getString(uri.toString().then((HttpRequest req) ...
According to the W3 XMLHttpRequest Specification:
(In the send() method) The argument is ignored if request method is GET or HEAD.
So simple answer to this question is no. sendData cannot be appended to a GET request, this is by XMLHttpRequest specification and not a limitation of Dart.
That said, for requests like this it may be more readable and idiomatic to use HttpRequest.getString
HttpRequest.getString(_url + sendData).then((HttpRequest req) {
// ... Code here
}).catchError(_onLoadError);
If you want to generate a valid URL from url (String) + query parameters (Map) , you can do the following :
Uri uri = Uri.parse(url).replace(queryParameters: parameters);
String finalURL = uri.toString();
url is a String and parameters is a Map

Get request response is in weird format

I send a get request to a local (separate from app) jetty web server
RestClient.get("ip/command/core/get-version", {})
Then I do a JSON.parse() on the response.
As a result I get
{"revision"=>"r2407", "full_version"=>"2.5 [r2407]", "full_name"=>" [r2407]", "version"=>"2.5"}
What's wrong? How do I turn it into a hash, so I can extract the full_version property?
String returned by service is html encoded. Try decoding it first:
JSON.parse(CGI.unescape_html(response_body))
Your JSON response looks to be encoded into HTML entities.
If you are using Ruby, try decoding the response using CGI.unescape_html prior to running JSON.parse. Running the result of that method through JSON.parse should give you your hash.

RestResponse is null on POST request using RestSharp

I am making a POST request with RestSharp (on windows phone 7.1 client). I sent string to a service in a request body. Looks like the service is successfully called and it returns proper value (integer), however response object is null:
client.ExecuteAsync<T>(request, (response) => {
data = response.Data; // response is null in debugger
});
I cant understand why is that so.
<T> isn't a valid value for that call. I'm not sure that would even build there unless you've wrapped it in a generic method.
Also, is the response coming back as plain text? What's the Content-Type returned? Most likely, you should just use ExecuteAsync(request, callback) without the generic parameter and grab the data out of response.Content which is a string of the response body. response.Data is for the automatically deserialized XML or JSON (or custom) response if you use the generic method overload that specifies a type to deserialize to.
This seems to be an ongoing issue with RestSharp asynchronous calls - for HTTP transport errors ErrorException object is useless (returns null). Check the StatusCode property if it returns with anything but HttpStatusCode.OK. StatusDescription is not extremely useful either as it doesn't match complete status message from server response payload.

Resources