I know that in GRAILS/GROOVY
def content=urlrestservicestring.toURL().getBytes(requestProperties: ['User-Accepted': username])
is a short form to have all the byte content (for example for PDF donwload), but I don't know all the request properties available for URL for richer connections, for example for POST method (this is a GET call) with payload in json. Is it possible? In which way?
It looks like per requestProperties you can set request headers only which might help for simple cases.
On the other hand if you want to do something more complex, like a POST, you have to use a propper HTTP-client.
In Groovy there's an idiomatic HTTPBuilder which is very straight-forward and easy to use, or Grails own RESTBuilder
UPDATE:
Using HTTPBuilder the download could look like:
import static groovyx.net.http.HttpBuilder.configure
configure {
request.uri = "http://example.org/download"
request.contentType = 'application/json'
}.post {
request.headers.username = 'Scarpanti'
request.body = [ some:'json' ]
Download.toStream delegate, response.outputStream // from grails
// or
// Download.toStream delegate, file
}
see also ref-doc
Related
I have a rest and a microservice.In microservice i have a table and i want that table data to be fetched to rest and i have written the below way in a rest demoController.
def result = restBuilder().post("http://localhost:2222/api/microservice/fetchData"){
header 'authorization', 'fdgtertddfgfdgfffffff'
accept("application/json")
contentType("application/json")
json "{'empId':1,'ename':'test1'}"
}
But it throws an error "No signature of method: demoController.restBuilder() is applicable for argument types: () values: []".How should i fetch data from a microservice to rest?
You are calling a method named restBuilder() and that method does not exist. If you want that to work, you will need to implement that method and have it return something that can deal with a call to post(String, Closure).
You probably are intending to use the RestBuilder class. The particulars will depend on which version of Grails you are using but you probably want is something like this...
RestBuilder restBuilder = new RestBuilder()
restBuilder.post('http://localhost:2222/api/microservice/fetchData'){
header 'authorization', 'fdgtertddfgfdgfffffff'
accept 'application/json'
json {
empId = 1
name = 'test1'
}
}
You may need to add a dependency on grails-datastore-rest-client in your build.gradle.
compile "org.grails:grails-datastore-rest-client"
I hope that helps.
We currently have a generic MVC method that GET's data from ASP.NET Web API
public static T Get<T>(string apiURI, object p)
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(Config.API_BaseSite);
HttpResponseMessage response = client.GetAsync(apiURI).Result;
// Check that response was successful or throw exception
if (response.IsSuccessStatusCode == false)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
throw new HttpException((int)response.StatusCode, responseBody);
}
T res = response.Content.ReadAsAsync<T>().Result;
return (T)res;
}
}
Our question is:- obviously, we can not send 'p' as you would with a post,
client.PostAsync(apiURI, new StringContent(p.ToString(), Encoding.UTF8, "application/json")
but how we go about sending this object / JSON with a get.
We have seen sending it as part of the URL, however, is there an alternative?
GET sends the values with the query string (end of url), in regards to "but how we go about sending this object / JSON with a get. We have seen sending it as part of the URL, however, is there an alternative?".
The alternative is POST or PUT.
PUT is best used when the user creates the key/url. You can look at examples such as cnn.com - where the URL's are just short versions of the article title. You want to PUT a page at that URL.
Example:
http://newday.blogs.cnn.com/2014/03/19/five-things-to-know-for-your-new-day-wednesday-march-19-2014/?hpt=hp_t2
has the url of "five-things-to-know-for-your-new-day-wednesday-march-19-2014", which was generated from the article title of "Five Things to Know for Your New Day – Wednesday, March 19, 2014"
In general, you should follow these guidelines:
Use GET when you want to fetch data from the server. Think of search engines. You can see your search query in the query string. You can also book mark it. It doesn't change anything on the server at all.
Use POST when you want to create a resource.
Use PUT when you want to create resources, but it also overwrites them. If you PUT an object twice, the servers state is only changed once. The opposite is true for POST
Use DELETE when you want to delete stuff
Neither POST nor PUT use the query string. GET does
I need to make a secure POST to https://example.com/api/login with parameters Username and Password. I'm trying to use the wslite plugin with Grails, but I can't figure out the syntax. I've checked the unit tests at github, but none of them have given me what I need. Maybe I'm just failing to connect the dots.
Anyway, does anyone have an example of multiple parameters to a POST? Thanks!
Try following example to post your request.
def client = new RESTClient("https://example.com/api/login")
// for testing only!
client.httpClient.sslTrustAllCerts = true
def response = client.post() {
charset "UTF-8"
urlenc username: "test", password: "test" // here you can provide your params as a map
}
This might be a noob question but i've been fiddling with it for hours now and wasn't able to find the solution.
I would like to send a POST request with form data using grails,
in jQuery this following 1 liner works as I wish:
$.post('<SOME SERVER URI>', {param1: 'p1'}, function(data) {console.log(data);})
but the following Grails code doesn't:
import static groovyx.net.http.ContentType.JSON
import static groovyx.net.http.Method.POST
import groovyx.net.http.HTTPBuilder
...
def http = new HTTPBuilder(<SERVER BASE URI>)
http.request(POST, JSON) {
uri.path = <REST OF URI>
uri.query = [param1: 'p1']
response.success = { resp, json ->
println 'success'
}
}
I think it has something to do with the data being sent, as the request leaves but fails (facebook graph is the base uri...)
the jquery code sends the data as form data, but i'm not sure thats the problem
Thanks!
It seems that facebook are really stickt on the params, and by sending 2 extra params facebook would not process the request, and simply return 400.
Thanks so much!
I've got a simple Grails app with the following RESTful uri...
http://localhost:8080/kennis-api/funds/test/700
The mapping in my URIMappings is
"/funds/test/$fcode" (controller: "fundCache"){
action = [GET: "show"]
}
In my controller, I need to extract the request URI, in this case "/funds/test/700", but invoking request.uri or request.getRequestUri does not work. I tried using request.requestURL, but that gives me
http://localhost:8080/kennis-api/grails/fundCache/show.dispatch
Is there a special member or function from which to get the request uri?
Its Simple, You need the Original address, that is same as the one where your response will be forwarded, its simply stored in the Request, and can be retrieved by:
.
String originalURI = request.forwardURI
//Do this where request is available, ex: Controllers :)
// Everywhere else you can use RequestContextHolder
.
.
Hope that helps
Regards
Kushal