Setting up a Restful POST request using xml - java

I'm working on setting up a RESTful request for the application I'm working on and I wanted to use xml as the request in the uri instead of allowing the client to supply the parameters in the URI itself.
I'm looking to have the URI like so: someurl/service/request
instead of: someurl/service/request?id={id}&name={name}
I have been searching the web to see what the convention should be when creating the POST request. Can anyone kind of help point me in the right direction on how I should set up this POST request allowing the client to use xml?
Not sure if it is relevant but I'm setting up the server side code in JAVA using the SPRING 3.0 framework. Please let me know if I need to supply more details.
Thanks for your help!!

You can put parameters into the body of the request. They are the same format as appending them to the URL. Eg:
POST /path/script.cgi HTTP/1.0
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
home=Cosby&favorite+flavor=flies
You can do that in prototype pretty easily with:
new Ajax.Request('someurl/service', {
method: 'post',
postBody: 'home=Cosby&favorite+flavor=flies',
encoding: 'UTF-8'});
To add your xml file, just append it to your postBody with some sort of delimiter so your cgi knows where parameters end and where xml begins.
I think that's what you were looking for, hope it helps.

You can pass whatever you want in your POST body. So if you want to use XML, you can use XML. Example:
POST /car
Content-Type: text/xml
<car>
<date>10-10-2007<date>
<type>Corvette</type>
</car>
HTTP/1.1 201 CREATED
I think all the REST API frameworks let you easily specify XML in the client request and server response. See Restlet's quick start for an example.

Related

java httpServer Post request work

I'm start learning java programming, and I want make a simple server application. I read about com.sun.net.httpserver.HttpServer and find a good example on this link: https://github.com/imetaxas/score-board-httpserver-corejava.
I understand how to do Get-request in url, but I don't know how POST works. I think it must be sent a form or data on the server.
I attach the link of project, which I'm learning, in readme the author wrote http://localhost:8081/2/score?sessionkey=UICSNDK - it's not working...
I wrote in url and get sessionkey: "localhost:8081/4711/login --> UICSNDK"
I wrote in url this for Post request: "localhost:8081/2/score?sessionkey=UICSNDK" - not working and in chrome return 404 bad request
3.wrote in url this:"localhost:8081/2/highscorelist"
Please help me, I am beginner.
The difference between GET and POST is that with a GET request the data you wish to pass to the endpoint is done by modifying the url itself by adding parameters to it.
With a POST any data you wish to send to the endpoint must be in the body of the request.
The body of a request is arbitrary data that comes after a blank line in the header The reqiest has the request line, following by any number of header attributes, then a blank line.
The server would need to know what the format of the body of the request was and parse it as appropriate.
Of course 'modern' frameworks like jax-rs allow you to automatically convert request data to objects, so that it is much simpler.

Sending Query Parameters encoded in a URI on a Post which also has json

I have a server that handles a POST request with JSON. It also looks and decodes query parameters from the URI. My Java Client currently uses HTTPPost to send across the Json with ContentType application/json.
I wonder whehther URLEncodeUtil method format would be able to accomplish this. Except the documentation mentions
suitable for use as an application/x-www-form-urlencoded list of
parameters in an HTTP PUT or HTTP POST.
So my question is
1. Would this work with ContenType set to application/json.
2. Is there another way to accomplish what the Server requires, ie: have JSON as well as Query parameters encoded in the URI.
There are two official methods of posting form data via the (HTML spec). The pertinent value is application/x-www-form-urlencoded which adds a ? along with the name/value pairs encoded in the URL. If the form method is POST then it will be the first line after the HTTP POST statement.
Everything we do with HTTP in REST web services is valid HTTP, but not for HTML. So the application/json can have a combination of the application/x-www-form-urlencoded style parameters and the JSON payload.
The HTTP request will look something like this:
POST /blog/posts?myparam=Something%20Good&token=donotdothis
Accept: application/json
Content-Type: application/json
Content-Length: 57
{"title":"Hello World!","body":"This is my first post!"}
Also spelled out here: http://www.jsonrpc.org/historical/json-rpc-over-http.html
It's the ? that marks the beginning of extra parameters. So while that is technically legal, it does beg the question why everything you need to post can't be part of your JSON. The downside of this approach is that the query parameters are all part of your HTTP logs and is very visible. You definitely should not use this approach with passwords or any other personally identifiable information. Depending on privacy laws in your country, you want to minimize unnecessary records to make compliance much easier.

Redirecting REST request using Servlets

Here is my issue. I want to be able to receive a REST request at an url like
localhost:8080/API to some other address like example.app/API, however I want to add some extra fields to the existing REST request like uuid and user_id which are generated by some Java class or extracted from another Rest service.
So for example I get following request:
GET /API/myfunc HTTP/1.1
Host: www.example.com
And resend a request
GET /example.app/API?uuid=1231231231231&user_id=3 HTTP/1.1
Host: www.example.com
Now this is simple if its a GET request, but what if it's a POST request?
Is there a already made solution to this problem?
UrlRewriteFilter [1] might help you here.
Such a filter allows you to define advanced redirecting rules and gives you access to the request and response objects (e.g. you can use request.addParameter(...))
Check the <run> element and <class-rule> element sections from [2].
[1] https://stackoverflow.com/questions/tagged/tuckey-urlrewrite-filter
[2] http://cdn.rawgit.com/paultuckey/urlrewritefilter/master/src/doc/manual/4.0/index.html

Can I rewrite a URL, adding query params and preserve the form data?

I have a rule like:
RewriteCond %{HTTP_HOST}:%{QUERY_STRING} ^(\w+)\.t(.*)\.(\w+)?\.sprawk\.com:(.*)$
RewriteRule ^(.*) /api/translateHtmlPublic?tl=%1&su=%2&p=$1&q=%4 [B,PT,L]
which works great for GET requests.
However, for POST requests, the q parameter is null (which I expected) but inside my Java servlet, both the HttpServletRequest.getReader() and HttpServletRequest.getInputStream() give no data.
Using Firefox Live headers, I see that I am sending:
POST /uid/contactSend.cfm HTTP/1.1
Host: fr.t51940.local.sprawk.com
Connection: keep-alive
Referer: http://fr.t51940.local.sprawk.com/uid/contact.cfm?country=137
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 146
userName=Nic&queryCountry=Libya&queryCode=137&userEmail=n.cottrell%40idea.int&Comment=Just+testing&captcha=Quotas&Submit=--+Envoyer+Commentaire+--
I know that the servlet is receiving it as a POST since the doPost method is triggered. I understand that Apache 2.x should automatically preserve POST data during a simple rewrite, but maybe the addition of parameters is wiping the content data?
Update: I just realised (by dumping out all parameters) that the userName, queryCountry, queryCode parameters are getting correct values via the request.getParameter(String) method. The problem is that I need to be able to separate the original form parameter names from the ones I introduction in the RewriteRule.
The parameters of a POST are in the body, not the header. You can rewrite the URL as much as you like without affecting them.
The body of a POST request whose content type is application/x-www-form-urlencoded consists only of parameters that are retrieved via request.getParameter(). Reading the body via request.getInputStream() and request.getReader() will deliver nothing. (Servlet Specification 3, #3.1.1)
According to Servlet Specifcation #3, the parameters you add to the URL should be retrievable via getParameter().
There is no way to distinguish POST parameters in the body from URL parameters in the header. There is probably therefore something wrong with your solution, or your problem.

is there any tool to simulate http requests in java

I am trying to simulate HTTP requests in Java with the URL class and the HttpURLConnection class, the GET requests are easy to simulate while some POST requests seem harder because most POST request need Cookie in the request header. Some cookies were set by the HTTP response in the Set-Cookie field and I can get them by the function provided by HttpURLConnection, but I found that other cookies may be set by JavaScript and I have no way to handle them, so I wonder is there any packaged tool to simulate HTTP requests in Java?
try Apache commons Httpclient:
http://hc.apache.org/httpclient-3.x/
Why do you need to generate HTTP requests? Do you want to perform some stress tests?
I'd advise using something like JMeter (you can find a brief tutorial here).
Hope this helps something, it's better to avoid reinventing the wheel (if you need something like this, but it wasn't clear for me from your question).
For the cookie set with Javascript, you could try to parse the HTTP response, extract the cookie information and set it for your next request
For example, lets say, the response has code which calls a setCookie() function (setCookie is user-defined javascript function),
...
//some javascript code
setCookie("username", "johndoe");
//some more javascript
...
then you would extract the line setCookie() and the parse it for the name and value

Categories

Resources