I have a Restful service with Jersey where I return Json data, the problem is when I try to get the data with $.ajax I'm not able get it.
My Restful service is:
#Path("/RegistroJson")
public class RegistroJson {
#GET
#Path("/get/{param}/{param2}/{param3}")
#Produces(MediaType.APPLICATION_JSON)
public Usuario htmlHello(#PathParam("param") String nick,#PathParam("param2") String pass,#PathParam("param3") String email) {
Usuario u=new Usuario();
u.setPass(pass);
u.setUser(nick);
u.setEmail(email);
return u;
}
I need the json in the web but I'm not able to get it with this:
$.ajax({url: "http://localhost:8080/RestWebService/rest/RegistroJson/get/emilio/adf/asdf"})
I use that command with this service(http://rest-service.guides.spring.io/greeting) and it works correctly so I think the problem is in my rest service
Could you help me with this?
Thank you
If you go to this rest url with browser, do you receive json data? In $.json() you need to add an success action when your received data will be accessible. You can do this by adding to {} option success:function(f){ console.log(f) }
Related
I have a client application requesting a list of channels from a webservice. Is it possible to take the "response" from the web service and store it in an ArrayList?
Meaning if I wanted to store a list of channels for example, it would normally come from the web service as a response, typically from ResponseBuilder.
And I want to store it in an ArrayList from the client, like List.
How would I go about doing that?
You can use TypeReference to instantiate your Channel object list, here is an example:
import com.fasterxml.jackson.core.type.TypeReference;
public class ChannelClient {
public void getChannels() {
Response serviceResponse = client.target("http://your_service_url/channels/").
request(MediaType.APPLICATION_JSON).get(Response.class);
String responseString = serviceResponse.readEntity(String.class);
List<Channel> list = new ObjectMapper().readerFor(new TypeReference<List<Channel>>() {
}).readValue(responseString);
}
}
Make sure to have Jersey JSON Jackson jar in your dependencies, you can get it from here
https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson/2.26-b07
EDIT: In case you want to consume MediaType.TEXT_PLAIN response, you will just change the request method argument to your specified type like this:
Response serviceResponse = client.target("http://your_service_url/channels/").
request(MediaType.TEXT_PLAIN).get(Response.class);
I am trying my first web app service using Azure services. I've created it in VS, and it works locally. All it does it return a string that says "hello user" is JSON.
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
[WebGet(UriTemplate = "/DoWork")]
public string DoWork()
{
// Add your operation implementation here
return "hello user";
}
// Add more operations here and mark them with [OperationContract]
}
}
Problem is when I publish it, says successful. I can see it running on portal.
When I goto published site I get the standard THIS WEB APP HAS BEEN SUCCESSFULLY CREATED, but... when I add the /DoWork to the URL I get HTTP error 404.
I know I must be missing something simple...
any ideas?
you're missing the name of the service. In your case would be something like:
http://engineappservicev001.azurewebsites.net/something.svc/dowork
More info in here:
http://www.codeproject.com/Articles/571813/A-Beginners-Tutorial-on-Creating-WCF-REST-Services
I am working on some web servers and I have to sent some data to the web service and get back a status code.. I am thinking maybe this should be a POST and not a GET but I would like to hear from all the pros out on the internet.
Here is my client code using Spring RESTTemplate
vars.put("lastName", "JOHN");
vars.put("firstName", "SMITH");
vars.put("middleInitial", "");
vars.put("socialSecurityNumber", "111-11-1111");
vars.put("Type","A");
vars.put("FileNumber","");
vars.put("EISNumber","");
String jsonreturn = restTemplate.getForObject("http://" + mRESTServer.getHost() + ":8080/services/api/checkstatus", String.class, vars);
Now here is my service side code (Spring MVC RESTful service). I would think all the fields I entered in the client would be in the ModelMap object but its not
#RequestMapping(value = "/checkstatus", method = RequestMethod.get)
#ResponseBody
public ResponseEntity<String> getCheckEnrollStatus(ModelMap model) throws ResourceNotFoundException
{
logger.debug("Looking for Status: " + model.toString());
}
So I have two questions:
1) Should I change the GET to a POST due to senting alot of data to the server?
2) If I leave it as a get why is my ModelMap emply?
Please help me out
For your ModelMap to be populated you probably need to annotate it with #RequestBody.
As the comment has pointed out you can't have a request body with a GET as per the specification. So you would either need to make the parameters part of the URL and use get or convert to POST.
Though POST seems to not fit with the purpose of your call.
Normally I'd say this should be a GET, but I noticed you have socialSecurityNumber as one of your parameters. You definitely do NOT want that to be part of your URL. Check out RFC 2616 section 15.1.3
Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead
Do a POST.
get as it is not changing anything onserver just returning data here is the spec.
Use request parameters like this
#RequestMapping(value = "/checkstatus", method = RequestMethod.get)
#ResponseBody
public ResponseEntity<String> getCheckEnrollStatus(#RequestParam final Long id)
or uri parameters, like
#RequestMapping(value = "/checkstatus/{id}", method = RequestMethod.get)
#ResponseBody
public ResponseEntity<String> getCheckEnrollStatus(#PathVariable final Long id) throws ResourceNotFoundException
{
I am currently developing a web app which should do restful service calls to existing web service api.
What I have is the base URL and the API names.
Any help on how do I start working on it?
I suppose I need to use httpbuilder for the base url I have, then followed by /api name. But how do I test it on grails if its working?
When I paste the base url on the browser it does return some xml information, so what I need is to do it on grails instead.
XML response when I paste the url through browser
<ns1:createNewUserResponse>
<userId>21</userId>
</ns1:createNewUserResponse>
So I need to be able to get this response through my web-app (grails) instead of pasting it on the browser.
EDIT*
this is a good example I found useful
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
def http = new HTTPBuilder( 'http://ajax.googleapis.com' )
// perform a GET request, expecting JSON response data
http.request( GET, JSON ) {
uri.path = '/ajax/services/search/web'
uri.query = [ v:'1.0', q: 'Calvin and Hobbes' ]
headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
// response handler for a success response code:
response.success = { resp, json ->
println resp.statusLine
// parse the JSON response object:
json.responseData.results.each {
println " ${it.titleNoFormatting} : ${it.visibleUrl}"
}
}
// handler for any failure status code:
response.failure = { resp ->
println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
but i do not understand the query part and how do I alter it to my need?
the URL I have contains credential of username and password, the response should return a securityToken which I need to get it out from the results. Any help would be greatly appreciated!
You can start with groovy-wslite, it provides both SOAP and REST webservice clients.
To make a call to a resfull service look at Groovy HttpBuidler - http://groovy.codehaus.org/HTTP+Builder
I have deployed a simple hello service in jboss server. I can view the wsdl file. Can someone help me with the client side. I mean how to access this service? Is there any way to access from web browser? Method deployed is
#WebMethod
public String greet( #WebParam(name = "name")
String name )
{
return "Hello" + name;
}
Try to know what is the wsdl url to access the service which you have just exposed. It might most probably be something like "http://localhost: < port-number >/ems-ejb/?wsdl"
If you type the same in the browser, you should be able to see the wsdl file (page with full of xml tags).
Once done, follow the steps provided here
Example on how to call the method once client stub is generated
String endpoint = "your wsdl url";
GreetImplServiceLocator objGreetImplServiceLocator = new GreetImplServiceLocator();
java.net.URL url = new java.net.URL(endpoint);
GreetIntf objGreetIntf = objGreetImplServiceLocator.getFaultImplPort(url);
String greetings=objFaultIntf.greet("stackoverflow");