Send error message as JSON object - java

I have two servlet: first servlet is similar to a client and creates an HttpURLConnection to call the second servlet.
I would like send a special error, formatted like a JSON object, so I call sendError method in this way:
response.sendError(code, "{json-object}")
But in the first servlet when I read error with getResponseMessage method I just get standard HTTP message and not my json object as a string.
How I can get my json string?

From the HttpServletResponse#sendError() javadoc:
The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html", leaving cookies and other headers unmodified. If an error-page declaration has been made for the web application corresponding to the status code passed in, it will be served back in preference to the suggested msg parameter.
So with this approach you have no other option than extracting the message from the HTML response yourself. JSoup may however be useful in this.
To achieve what you want, you need to set the error code and write the response yourself, e.g.
response.setStatus(code);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Instead of code you could by the way also use one of the HttpServletResponse.SC_XXX constants for this.

Related

Hiding Parameters in url while sending url through response.sendRedirect method

I am sending url to another server through response.sendRedirect() method and it is generating pdf for me. I am passing all the parameters but one of the parameter data is exceeding length due to which browser is not able to handle it and request is getting blocked.
I know through Post method we can hide url Parameters and response.sendRedirect() uses GET method. Is there any POST method like sendRedirect through which we can access another server url directly through servlet? Thanks in advance.
With response.sendRedirect(newUrl) you send back a HTTP status 302 with a new Location=newUrl in response header. Thus, you cannot force browser to make POST instead of GET method.
What you could do is to consume a pdf file from within your server code and return it to the client, hiding thus from client the actual target location. You can then build any request with method and parameters you want to the new location if it accept it.
See, for example, this tutorial how to make a request to another server from your servlet http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/

RESTService returns HTML when writer does not contain data

I'm currently developing RESservices using the customService bean. One thing I've noticed is that for some reason when I dont use the responsewriter object but only set the response status using engine.getHttpResponse().setStatus(404) (for instance). The header is correctly set ( 404 ) but there is still some html generated.
I've already tried to set the rendered property on the view tag (of the xpage) to false but that doesn't seem to do the trick. Is there some documentation on how to use the CustomServiceBean and not returning any data?
Setting the Status is a good approach, so the API is easy to handle. However you want to consider:
set the content type to what would actually be rendered if you had a result. If you don't set response.contenttype it defaults to HTML
404 is meant for navigation/urls. Since your XPage renders a result, the request found a valid URL. That based on user and/or parameters there's no result isn't therefore a 4xx class of error, but rather a 5xx. Pick one of them.
when testing use wget or curl, so you can be sure the browser doesn't do the HTML
Let us know how it goes
I think returning a 404 response causes always HTML data as it normally gives you the error message etc.
If you don't want to response with any data just return an empty JSON object - as I assume you return JSON when you HAVE data, right?
dont set 404 status ,set null for this case,ant error status like 404 means creating html for that

Determine type of requested content inside doGet

I have an iframe and a textbox(to enter required url) in my main page, so when user enters required URL I load requested page to iframe.
I am using HttpServlet to handle get requests through doGet. I need to distinguish the requested content type, because if it is a file(img or script) I just read it and return, but if it is an html page, I make some modifications.
I tried to use request.getContentType() inside doGet but it returns null. So is there any way to do this? Thank You
HttpServletRequest#getContentType() returns the value of the Content-Type header if there is one.
You need to specify it when sending the request. You can use Javascript to do this.
Alternatively, but not ideally, you could use a query string parameter to hint at content type.
That's for getting the content type of the request body.
If you want to specify what content the response should have, you need to specify the Accept header with an appropriate media type.
You can alternatively, do URL extension matching. For example, www.host.com/some/path.xml would return XML.
The request.getContentType() method will only return a value if your request body contains data. Since it's a GET it does not contain any body. If you have any data it's either part of the URL or in a query-string attached to the URL. It's pointless to declare Content-type in GET requests, so there is no header to read.
You have to look for the data that you need in your request URL.
If it's a URL generated by a link or image, then get the name and extension from the URL.
It it's generated by a script, it might have that information elsewhere, such as in some variable in the query string (?file-name=xyz&file-type=png for example) or in extra path information (/servlet/xyz/jpeg for example). It depends on how your client is requesting the data.
Do you want to know content type of request, mabye you don't know what for you requests check your URL. If your request contain no data you can request.getContentType should return null value. You can do it on response not request. Mabye you can pass parameter do define what response do you want. I suppouse you have to check response type to determine behaviour of your application depends on the response type not request. Simple GET request only wait for response. And based on that response do some actions.

Handling different XML response documents with one SAX Handler

I am developing a Java application that makes an HTTP Request to a web service, and XML is returned. If the response code is 200, then a requestSucceeded() callback method will send the XML to a SAXParser with a different SAX Handler, depending on what web service is being called. If the response code is not 200, then a requestFailed() callback method is being called.
The web service that I am calling will return two types of XML documents (with a response code of 200): an XML document containing the successful response information, or an XML error document containing error information (for example, if one of the request parameters wasn't formatted correctly).
My question is this: Given my current setup, what is the best way to look for / handle both kinds of XML documents (a successful XML response or an XML error document)? The SAX Handler is looking for all of the relevant response information and it is storing that information into an object, which is then processed by my application. Is there a better solution than just always first looking for the unique XML Error tags?
Thanks!
Option #1 - Change Respose Code
Why are you returning an error with response code 200? 400 (Bad Request) or another error code might be a better option. Then you could process the XML based on the response code.
Option #2 - Swap Content Handlers
Below is a link to one of my previous answers where I explain how to swap content handlers while processing the document. You could have one content handler that determines if the response is content or error, and then swaps in the appropriate content handler to process the rest.
Using SAX to parse common XML elements
Option #3 - Use JAXB
If the end result is that the XML will be converted to an object, have you considered using JAXB? It will build an object based on the XML based on what is returned.

AS2: Does xml.sendAndLoad use POST or GET?

All,
I'm trying to find out, unambiguously, what method (GET or POST) Flash/AS2 uses with XML.sendAndLoad.
Here's what the help/docs (http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00002340.html) say about the function
Encodes the specified XML object into
an XML document, sends it to the
specified URL using the POST method,
downloads the server's response, and
loads it into the resultXMLobject
specified in the parameters.
However, I'm using this method to send XML data to a Java Servlet developed and maintained by another team of developers. And they're seeing log entries that look like this:
GET /portal/delegate/[someService]?svc=setPayCheckInfo&XMLStr=[an encoded version of the XML I send]
After a Google search to figure out why the POST shows up as a GET in their log, I found this Adobe technote (http://kb2.adobe.com/cps/159/tn_15908.html). Here's what it says:
When loadVariables or getURL actions are
used to send data to Java servlets it
can appear that the data is being sent
using a GET request, when the POST
method was specified in the Flash
movie.
This happens because Flash sends the
data in a GET/POST hybrid format. If
the data were being sent using a GET
request, the variables would appear in
a query string appended to the end of
the URL. Flash uses a GET server
request, but the Name/Value pairs
containing the variables are sent in a
second transmission using POST.
Although this causes the servlet to
trigger the doGet() method, the
variables are still available in the
server request.
I don't really understand that. What is a "GET/POST hybrid format"?
Why does the method Flash uses (POST or GET) depend on whether the data is sent to a Java servlet or elsewhere (e.g., a PHP page?)
Can anyone make sense of this? Many thanks in advance!
Cheers,
Matt
Have you try doing something like that :
var sendVar=new LoadVars();
var xml=new XML("<r>test</r>");
sendVar.xml=xml;
sendVar.svc="setPayCheckInfo";
var receiveXML=new XML();
function onLoad(success) {
if (success) {
trace("receive:"+receiveXML);
} else {
trace('error');
}
}
receiveXML.onLoad=onLoad;
sendVar.sendAndLoad("http://mywebserver", receiveXML, "POST");
The hybrid format is just a term Macromedia invented to paint over its misuse of HTTP.
HTTP is very vague on what you can do with GET and POST. But the convention is that no message body is used in GET. Adobe violates this convention by sending parameters in the message body.
Flash sends the same request regardless of the server. You have problem in Servlet because most implementation (like Tomcat) ignores message body for GET. PHP doesn't care the verb and it processes the message body for GET too.

Categories