How to (simulate) a POST in jUnit - post

I am trying to have a server respond to a request which needs a XML structure. The easiest way I thought would be to create a POST with a string containing the XML, using the Play Framework.
However, I cannot seem to get it to work. I am calling the test with the following code:
Map<String,String> map = new HashMap<String,String>();
map.put("data", xmlString);
Http.Response response = POST("/server/", map);
When on the server checking the parameters it is not in it as it returns false:
params._contains("data")

Related

Different response for same API method

New to the RestAssured and just checking different ways of working with REST APIs. For testing I am using http://dummy.restapiexample.com/api/v1. In this I am trying the GET employee method using RequestSpecification and groovy way but I am getting different response.
My short code is:
RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1";
RequestSpecification request = RestAssured.given();
Response response = request.get("/employee/72100");
System.out.println(response.getBody().asString());
given().baseUri("http://dummy.restapiexample.com/api/v1").get("/employee/72100").then().log().body();
And output I am getting is:
{"id":"72100","employee_name":"mpr51_0280","employee_salary":"123","employee_age":"23","profile_image":""}
<html>
<body>{"id":"72100","employee_name":"mpr51_0280","employee_salary":"123","employee_age":"23","profile_image":""}</body>
</html>
I am not getting why it is returning response with HTML tags. Can anyone explain or give hint to get same response as first call to get method.
NOTE: You may or may not get details for employeeID 72100
You can use any employee ID from response of:
http://dummy.restapiexample.com/api/v1/employees
Because the Body contains it .
You can use below statement if you need only the response
given().baseUri("http://dummy.restapiexample.com/api/v1").get("/employee/72100").then().log();
OR
Response resp = given().baseUri("http://dummy.restapiexample.com/api/v1").get("/employee/72100");
System.out.println(resp.asString());

Proxying MultiPart form requests in Grails

I have a Grails controller that receives a DefaultMultipartHttpServletRequest like so:
def myController() {
DefaultMultipartHttpServletRequest proxyRequest = (DefaultMultipartHttpServletRequest) request
}
This controller acts as a proxy by taking pieces of this request and then resends the request to another destination.
For non-multipart requests, this worked fine, I did something like:
IProxyService service = (IProxyService) clientFactory.create()
Response response = service.doPOST(proxyRequest.getRequestBody())
Where proxyRequest.getRequestBody() contains a JSON block containing the request payload.
However, I do not know how to get this to work with multipart request payload, since the request body is no longer a simple block of JSON, but something like the following (taken from Chrome devtools):
How can I can pass this request payload through using my proxy service above, where doPost takes a String?
Have you tried
def parameterValue = request.getParameter("parameterName")
to get the parameter value?
If you see the method signatures for DefaultMultipartHttpServletRequest you will see there are methods for getting the files and other parameters separately because the request body is getting used to both upload the file and to pass in other parameters.

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

Invoke WCF Data Services Service Operation from iOS

How do I invoke a Service Operation in WCF from iOS?
I have a Service Operation defined in my WCF Data Service (tied to a stored procedure in my DB schema) that I need to invoke from iOS. Say I've got the following declaration in my .svc.cs file:
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public IQueryable<Foo> GetFoos(int param1, DateTime param2, string param3)
{
return CurrentDataSource.GetFoos(param1, param2, param3).AsQueryable();
}
And I've got it set up with the proper rights in InitializeService:
config.SetServiceOperationAccessRule("GetFoos", ServiceOperationRights.AllRead);
When I try to invoke this via HTTP POST from iOS, I get back an error wrapped in JSON:
Bad Request - Error in query syntax.
It seems like it doesn't like how I'm passing my parameters. I'm passing them JSON-encoded (using NSJSONSerialization to turn an NSDictionary into a JSON string) in the request body of a POST request. The same method works on another web service (.svc) not connected to WCF that has operations annotated the same way.
An answer to another question of mine in a similar vein suggests that data formats can be negotiated between client and server, and I've read that dates are a pain to format, so maybe it's my DateTime parameter that's a problem. But I've tried both the JSON format (\/Date(836438400000)\/ and /Date(836438400000)/) and the JSON Light format (1996-07-16T00:00:00) to no avail.
So my question is this: what is the proper way to invoke this operation? If I need to have my app tell the server what format to expect, how do I do that?
Update: I tried using the format datetime'1996-07-16T00:00:00' as mentioned in this question. Same error.
Update 2: The MSDN page for Service Operations seems to suggest that nothing besides Method = "POST" is supported when annotating the WebInvoke for a Service Operation. I tried removing everything from what is quoted in the above code and setting the method to POST. Same error.
Update 3: On Pawel's suggestion, I made a new Service Operation on my Data Service just like this:
[WebInvoke(Method = "POST")]
public IQueryable<string> GetFoos()
{
List<string> foos = new List<string>();
foos.Add("bar");
return foos.AsQueryable();
}
I was able to make it work in Fiddler's Composer pane by setting the method to POST, adding accept:application/json;charset=utf-8 and Content-Length:0 to the headers. Then I added a single int parameter to the operation (called param1). I set the body of my request in Fiddler to {"param1":"1"} and ran it (and Fiddler automatically updated my content-length header), and got the same error. I changed the type of my parameter to string and ran my request again and it worked. So my problem seems to be non-string types.
You need to send parameters in the Url and not in the request body.

How to capture http POST requests with browsermob-proxy and selenium

Hello trying to capture the actual POST data in an HTTP POST request using browsermob proxy + selenium test framework. So basically i'm running an automated test using selenium and I want to capture the key/value pairs and the actual POST data of a HTTP POST request during the test. Using the following logic I can only capture the key/value pairs of the POST header but not the actual POST data (aka the form field id values). Is there a way to actually capture the POSTDATA (like sniffing applications do such as tamper/live headers in firefox)?
ProxyServer proxyServer = null;
proxyServer = new ProxyServer(9101);
proxyServer.start();
proxyServer.setCaptureContent(true);
proxyServer.setCaptureHeaders(true);
Proxy proxy = proxyServer.seleniumProxy();
proxy.setHttpProxy("localhost:9101");
//selenium test config code, omitted for brevity
proxyServer.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
Header[] headers = request.getAllHeaders();
System.out.println("\nRequest Headers\n\n");
for(Header h : headers) {
System.out.println("Key: " + h.getName() + " | Value: " + h.getValue());
}
}
});
An alternate way I read about but could not get to work was to configure the following flags in the browsermob proxy server to true:
proxyServer.setCaptureContent(true);
proxyServer.setCaptureHeaders(true);
Then output the actual HAR file:
Har har = proxyServer.getHar();
Date date = new Date();
har.writeTo(new File("c:\\tmp\\har_" + date.getTime()));
To see the key/value pairs, POST Data, and actual content of the response... but when I parse the HAR file... I only see the key/value pairs of the POST header again... no POST data... no response content. I am only interested in the actual POST data though.
I also had same problem. As a solution, I captured all the data, converted the HAR file into JSON, and then filtered out only POST requests from the JSON file.

Resources