I am new to Rest web services, and I am trying to figure out what I am doing wrong. When I run on server with the address:
localhost:8080/rest/webresources/error
Then the output message I want (the error message) shows up.
But when I run on the server to show input values using:
localhost:8080/rest/webresources/inputvalues
it doesn't. What am I doing wrong? I feel like my path is wrong, and I tried different combinations of it, but it still gives me a 404 not found error.
#Path("error")
public class RestWeb {
#GET
#Produces(MediaType.TEXT_HTML)
public String getText() {
return "<body> Error. Invalid data. </body>";
}
#POST
#Produces(MediaType.TEXT_HTML)
#Path("/inputvalues")
public String getParamText(#FormParam("travel") String travel,
#FormParam("start") String start,
#FormParam("duration") String end,
#FormParam("party") String people) {
String returnString = processInput(travel, start, end, people);
return "<body> " + returnString + " </body>";
}
Assuming that the REST services were correctly written and deployed, the problem here is the lack of understanding of the way a POST Rest Service is expected to behave as.
From the comment section above it is clear that you are trying to call a POST API directly from a browser.
That can be done fine for a GET type of a service but won't work for a POST type service.
Reason
The REST API uses several HTTP methods to perform various actions on REST resources. Any REST API that uses a GET call can be invoked using a web browser.
A post service however expects a certain set of input parameters (Here in your case, form params "travel", "start", "duration" and "party" are required)
You cannot call POST API's directly by simple typing the path of the Service URL in the browser.
You can use tools like POSTMAN, RESTer and a lot of such software available on the web, with extensive tutorials on how to use these for POST type REST API calls.
Related
I want a online REST open API (POST Method), which accepts RequestBody as String only.
I have to ping a message to that open API.
restTemplate.postForEntity("myRequestUrl", "my message", String.class);
There are several websites which offer public APIs to test requests, including, but not limited to:
https://httpbin.org / http://httpbin.org/
https://webhook.site
https://test-api.k6.io
https://jsonplaceholder.typicode.com
https://reqres.in
https://fakestoreapi.com
You can also find a list of public APIs at https://github.com/public-apis/public-apis. Those are not necessarily test APIs, but they return real data. Maybe it is useful to somebody.
I have built a simple service in Spring:
#RequestMapping(value = "/list", method = RequestMethod.GET)
public #ResponseBody List<Person> eventList() throws ParseException {
return personDAOImpl.list();
}
When I invoke the corresponding URL, I see a JsonObject list like this:
[{"id":2,"name":"John"},{"id":3,"name":"Jack"},{"id":4,"name":"Sam"}]
This service will be invoked both from a mobile app (and I know how to use a Json response in this case) and from a browser, and so I want that the /list service returns a Json.
By now, if I write the url in a browser (typing localhost:8080/myproject/eventList) I simply obtain the aforementioned Json String displayed on the screen.
How could I obtain a user-friendly interface that shows to the user a more friendly, like if I used a jsp?
ps: I have already used a service that successfully returns a jsp page (using ModelAndView), and that shows a table with the items, but I repeat that I would like to get a json response and than parsing it in a different way depending from the client (web browser or mobile app).
Thank you in advance!
You could build a client app which makes requests to your API using JavaScript.
For example,
localhost:8080/jsp/home returns a jsp page Home.
The Home page makes AJAX request (using JavaScript) to localhost:8080/myproject/eventList and recieves the JSON object. jQuery.get()
The Home page adds (using JavaScript) some visual elements to html. jQuery.append()
That's all.
I am working on RESTEasy services to generate API for my application.
I tested with the below code to produce a simple string response,
#GET
#Path("/api")
public Response getUsers(#QueryParam("from") String from,) throws ProtocolException,
MalformedURLException, IOException {
return Response.status(200)
.entity("*************Hi Welcome*********************")
.build();
}
It is working fine with the following url
http://localhost:8080/myApp/f/api?from=any_string_here
But, this response available only while the query parameter value does not exceed 6246 characters.
If the query parameter value more than 6246 chars, there is no response available. Also, the browser network console shows the status code 400.
http://localhost:8080/myApp/f/api?from=more_than_6246_chars
I read that longer url needs to be send using POST, so I tried also with #POST method too for this, but browser network console shows the status code 405 and the following appears in eclipse console.
Apr 07, 2016 12:52:25 PM org.apache.tomcat.util.http.Cookies processCookieHeader
INFO: Cookies: Invalid cookie. Value not a token or quoted value
Note: further occurrences of Cookie errors will be logged at DEBUG level.
Is this longer URL is restricted by browser or RESTEasy application.
What would be the solution for this? Do I need to send more chars to my rest api parameter.
Webservers may reject requests if the URL exceeds a certain size.
Using a POST request alone does not help, you also need to decrease the URL size by putting URL parameters into the POST body.
You can try sending the parameters in request headers. I am using Jersey framework and angular JS in the front end. Sometimes I need to send a long JSON string for my application. I am sending it in the request headers and so far, I haven't got any issue like this.
My Rest Service class looks like below :
#Path("getStatus/agentName")
public class getStatus(){
#GET
public Response getStatus(#HeaderParam("header_name") String header_value){
String response = "Success" + header_value;
return Response.ok(response, MediaType.TEXT_PLAIN).build();
}
}
You can send your parameters in custom headers.
I think this should solve your problem.
Our development team is building an application that uses jasper-reports 6.2.0, spring-mvc 3.2.14, java-ee-7, tomcat 8 and in the front-end we use angularjs. Our rest requisitions are all made via ajax.
The application is entirely built to receive json objects as response for our requisitions, because our requisitions via angularjs are all made via Ajax. In a specific application feature we have a regular get requisition using window.location = url, because we need to return a streaming which is nothing more than a byte array containing a PDF file content.
That being said, when we have a back-end error while generating this PDF file our application redirects user to a blank screen with a json object printed in it.
I've already had experience in spring-mvc exception handling globally ou per exception case, using exception handling with ExceptionHandler annotation or per ControllerAdvice to generalize the exception handling, but always handling classes in the controller layer annotated with Controller returning a ModelAndView object, but never classes in the service layer annotated with Service.
My question is how to capture a exception and make the application redirects users to a error screen with some parameterized message when we have regular get requisitions.
In my experience, and even if it's not exactly an answer to the question, main issue is not server side but client side :
stop doing window.location = url to download Content-Disposition:attachement files in an RIA application. Particularly when the download can cause errors thrown to the client. really.
Libs like fileDownload ( https://github.com/johnculviner/jquery.fileDownload ) allow to download the file in background, avoiding all the mess when an error append, and the UI freeze waiting for the server response.
So lets say you want to take care of exception on client side on the basis of http status code then you can make a interceptor like :
var app = angular.module('appname',[]);
app.factory('myHandler', function ($injector) {
var interceptor = {
response: function (response) {
.
.
.
return response;
},
responseError: function (response) {
if (response.status == 401) {
location.href = "#/error";
}
else if(response.status == 403){...}
else if().....
return response;
}
};
return interceptor;
});
and inject it in your application as :
app.config(function ( $injector) {
$httpProvider.interceptors.push('myHandler');
...
});
now every request would first go here , check if error status or whatever you want it to and then if no error (in which case you dont change location.href) it continues ,magically to wherever it was going else goes to specified templateURL on the basis of routeProvider.
Helpful links injector, httpProvider
I have a 404 status error (page not found). I only want to send a request from my Android app to Mean.io web app through
the following url:
http://192.168.0.103:3000/auth/register
I have also tried:
http://10.0.2.2:3000/auth/register
I had already googled but both of the solutions above didn't worked for me. However the url: http://192.168.0.103:3000/auth/register does work
on my Chrome browser on my pc.
Here is the code:
public class AppConfig {
// Server user register url
//public static String URL_REGISTER = "http://10.0.2.2:3000/auth/register";
public static String URL_REGISTER = "http://192.168.0.103:3000/auth/register";
}
If you want to know where the variable URL_REGISTER gets used. It's getting used in the registerUser() method.
I'm posting the method through a link, because the method is too big to post it here. In the link below you can see that the URL_REGISTER gets used on line 10.
Link: http://pastebin.com/ttH6upnb
1 be sure you connect to the server
192.168 and 10.0 are local addresses (not going to internet)
beware, if you get 404, perhaps another server like proxy responds to you
2 read this: Using java.net.URLConnection to fire and handle HTTP requests
3 begin by getting page "/" and check the headers (good server, etc.)
4 then verify your code, step by step
5 check if GET or POST, and authentication is not easy (check the headers)