I have a RESTClient class, I want to do a POST to a web service.
My POST request will use JSON.
So in the Groovy class, the call looks like this:
def restClient = new RESTClient(url)
def bodyContent = "{\"products\":[{\"ProductId\":1,\"ProductName\":\"Product\"}]}"
response = restClient.post(
headers:['Authorization': auth],
contentType : jsonContentType,
body: bodyContent
)
the header and contenttype string is correct.
I put a JSON data as String type in the bodyContent and put into the body of the POST request.
I run this method and get error:
at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.setPropertiesFromMap(HTTPBuilder.java:1111)
at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.<init>(HTTPBuilder.java:946)
at groovyx.net.http.RESTClient.post(RESTClient.java:140)
at groovyx.net.http.RESTClient$post.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
So i wonder how can i make a POST request using RESTClient?
I look into the document http://groovy.codehaus.org/modules/http-builder/doc/rest.html here. The POST example is not applicable to my situation.
Related
I have a SoapUI REST (i.e. non-SOAP) mock service that returns a response for a POST request.
The request and response both contain JSON content.
At the moment, I can get it to return a static response and that works fine, but I want some of the values in the response to be dynamically sourced from the request.
So if I have this request:
{
"the_request":{
"abc":"123",
}
How can I get the value of "abc" copied in the response?
Investigation has lead me to believe I can do this via including a variable in the response, something like:
Response:
{
"the_response":{
"value_from_request":"${#MockResponse#Request#the_request#abc}",
"other":"stuff",
}
And then implementing a script to populate the variable in the response, via the Script tab.
How can I then populate this with data from the request?
Currently SoapUI just generates an empty value
"value_from_request":"",
Tried using mockRequest.requestContent in the Script tab, but have not found how to obtain the "123" value from it.
OK, worked this out. So the response message can simply reference a variable in the requestContext like so:
Response:
{
"the_response":{
"value_from_request":"${the_value}",
"other":"stuff",
}
And a groovy script can be used to parse the JSON request content and populate "the_value" or whatever you like in the requestContext:
// Parse the JSON request.
def requestBody = new groovy.json.JsonSlurper().parseText(mockRequest.getRequestContent())
// Set up "the_value" from the request message.
requestContext.the_value = requestBody.the_request.abc
// Bit of logging so can see this in the "script log" tab.
log.info "Value extracted from request: ${requestContext.the_value}"
I think the script should be like this
def requestBody = new groovy.json.JsonSlurper().parseText(mockRequest.getRequestContent())
context.setProperty("the_value",requestBody.the_request.abc)
i have a rest endpoint in my controller like this..
#RequestMapping(value = "/createFoo", method = RequestMethod.POST)
public ResponseEntity<Void> createFoo(#RequestPart(name = "foo") Foo foo,
#RequestPart(name = "file", required = false) MultipartFile file) {
service.createFoo(foo, file);
return new ResponseEntity<>(HttpStatus.CREATED);
}
how can i test this out using postman and curl? i need to send a json foo with or without a file. thanks in advance.
you can shorten it like this #PostMapping("/createFoo")
Firstly specify your method Post and url that postman requested it than
select form-data under Body section
Click key input area and change text to File
In addition parameter name need to be same as form-data variable
Example attached
Similar to this question, I need to send back JSON.
WCF ResponseFormat For WebGet
But I'm working from within a WCF Behavior being called by a BizTalk 2010 SendPort Adapter.
I'm inside this method:
public object BeforeSendRequest(ref Message request, IClientChannel channel)
So I have the Message and the channel that I can manipulate.
I think the direction is something like this:
1) //WebOperationContext.Current.OutgoingResponse.ContentType = “text/plain”;
or
2) OperationContext.Current.... something - but I don't know the object model well.
I'm currently using the MemoryStream:
byte[] byteArrayJSON = Encoding.UTF8.GetBytes(strJSON);
MemoryStream memStreamJSON = new MemoryStream(byteArrayJSON);
//WebOperationContext.Current.OutgoingResponse.ContentType = “text/plain”;
Message newMessage = Message.CreateMessage(MessageVersion.None, "", memStreamJSON);
...
request = newMessage; // substitute my new message for the original one.
My headers have this:
Content-Type: application/json
Accept: application/json
I think these are the lines I need, but still testing...
WebBodyFormatMessageProperty bodyFormat = new WebBodyFormatMessageProperty(WebContentFormat.Json);
newMessage.Properties.Add(WebBodyFormatMessageProperty.Name, bodyFormat);
It looks like maybe now I should pass XML and this will cause the serialization to happen? I'm now on to my next error:
System.ArgumentException: Encountered unexpected namespace 'http://schemas.datacontract.org/2004/07/System.IO'. The namespace must be empty.
Parameter name: ns
Going to try "raw":
WebBodyFormatMessageProperty bodyFormat = new WebBodyFormatMessageProperty(WebContentFormat.Json);
newMessage.Properties.Add(WebBodyFormatMessageProperty.Name, bodyFormat);
I am using webapp2 for development in App Engine. What I would like to do is to send a custom JSON formatted response in case of an error. For example when the request length is larger that a threshold, to respond with HTTP 400 and response body
{'error':'InvalidMessageLength'}
In webapp2, there is the option to assign error handlers for certain exceptions. For example:
app.error_handlers[400] = handle_error_400
Where handle_error_400 is the following:
def handle_error_400(request, response, exception):
response.write(exception)
response.set_status(400)
When webapp2.RequestHandler.abort(400) is executed, the above code is executed.
How is it possible to have different response formats (HTML and JSON) dynamically based on the above setup? That is, how it is possible to call different versions of handle_error_400 function?
Here is a fully working example that demonstrates how to have the same error handler for all kind of errors and if your URL starts with /json then the response will be an application/json (use your imagination on how you could make a good use of the request object to decide what kind of response you should provide):
import webapp2
import json
def handle_error(request, response, exception):
if request.path.startswith('/json'):
response.headers.add_header('Content-Type', 'application/json')
result = {
'status': 'error',
'status_code': exception.code,
'error_message': exception.explanation,
}
response.write(json.dumps(result))
else:
response.write(exception)
response.set_status(exception.code)
app = webapp2.WSGIApplication()
app.error_handlers[404] = handle_error
app.error_handlers[400] = handle_error
In the above example you can easily test the different behaviours by visting the following URLs that will return a 404 which is the easiest error to test:
http://localhost:8080/404
http://localhost:8080/json/404
I got a REST WCF Service running in .net 4 and I've tested the web service it is working and accepting HttpRequest I make to it. But I ran into a problem trying to access the HttpRequest body within the web service. I've tried sending random sizes of data appended on the HttpRequest using both Fiddler and my WinForm app and I can't seem to find any objects in runtime where I can find my request body is located. My initial instinct was to look in the HttpContext.Current.Request.InputStream but the length of that property is 0, so I tried looking in IncomingWebRequestContext that object doesn't even have a method nor properties to get the body of the HttpRequest.
So my question is, is there actually a way to access the HttpRequest request body in WCF?
PS:
The data inside the request body is JSON strings and for response it would return the data inside response body as JSON string too.
Much simpler, this answer on WCF + REST: Where is the request data? works fine.
Also, if your request body is deserializable, you can just pass a class. Barring some typos, this should work:
public class Banana
{
public string Colour;
public int Size;
}
...
[WebInvoke(
Method = "POST",
UriTemplate = "bananas",
ResponseFormat=WebMessageFormat.Json,
RequestFormat=WebMessageFormat.Json)]
string CreateBanana(Banana banana);
...
public string CreateBanana(Banana banana)
{
return "It's a " + banana.Colour + " banana!";
}
Doing POST with data {"Colour": "blue", "Size": 5} to this resource should return "It's a blue banana!".
Try with ((System.ServiceModel.Channels.BufferedMessageData)(((System.ServiceModel.Channels.BufferedMessage)((OperationContext.Current.RequestContext).RequestMessage)).MessageData)).Buffer
it has type System.ArraySegment<byte>
or read WCF + REST: Where is the request data?