Reload/History behaviour in Get and Post request? - java

I went thru http://www.w3schools.com/tags/ref_httpmethods.asp to read
about read vs post.Here is the description
To clear confusion, I am just taking scenario where user creates the customer on page 1(with the submit button) and
navigates to success page(page 2).
For reload (say user press F5 on success page) point, Get request is said to be harmless where in post request
"Data will be re-submitted".
My understanding in both request (GET/POST), data will be resubmitted
. so in customer scenario, two customer will be created when user
press F5 on page whether its post or get. So as per my
understanding, Data will be re-submitted in both GET/POST request and
none is harmless.Please correct my understanding if it is wrong?
For History point. It is said in GET request ,"Parameters remain in browser history" and for POST request
"Parameters are not saved in browser history". My question is if request parameters are not saved in
browser history in post request, how on click of F5 on success page duplicate customer is created. Are they stored
at some other location instead of browser history in post request?

I'll try to explain point by point:
About GET being harmless: Method GET is supossed to de idempotent, that means: given the same url and the same parameters it always should return the same result (user=34,date=01-07-2013 should return the same page) and SHOULDN'T change anything (do nothing more than a sort of query with "user" and "date"). Of course is quite common to break this rule and actually change the internal state (do an update or the like) that is the case that you're mentioning (page1 --> page2 creating something). POST requests don't have that requirement and are meant to change the internal state.
About parameters remaining in browser history: What they really mean is that in the GET request parameters are contained in the URL itself ( mysite.com?user=34,date=01-07-2013 ) so if you save the URL you also saving the parameters. In a POST request parameters go in the body of the request rather than as part of the URL; so you're right, old browsers used to only store the URL, nowadays browsers are optimized to store those POST parameters in an internal cache.

Related

How to retrieve access token from Reddit via OAuth flow with Java

I have my authorisation url - https://www.reddit.com/api/v1/authorize?client_id=xuJKekGTr1-V8Q&response_type=code&state=dfDfsd4gdf&redirect_uri=http://localhost:8080/redditimageuploader/callback&duration=permanent&scope=submit
But I don't really know what to do from here? I've found a few guides online but it's just a lot of jargon I don't really understand. When I click on the "allow" button, it takes me to the url that I defined as my redirect_uri, and appended to the end of the string is the state that I set, as well as code= and then a string - so I assume I need to do something with those, but I don't know what.
I was wondering if there is a super simple "explain like I'm 5" step-by-step guide on what to do from here?
It's a standard OAuth flow. From the doc :
When the user clicks the "Sign on with Reddit" button on your website, you must redirect the user to the authorisation URL at Reddit - the one in your question, starting with https://www.reddit.com/api/v1/authorize and enriched with the request params you specified. Reddit will then ask the user to sign in, and whether or not he wants to authorise your app access to the requested scope. See https://github.com/reddit-archive/reddit/wiki/OAuth2#allowing-the-user-to-authorize-your-application
If the user agrees, then Reddit will redirect the user to the redirect URI you specified as request param in the authorisation URL (in your case, http://localhost:8080/redditimageuploader/callback). Reddit will add a state request param: you need to ensure that this is the same as the one in your request.
Retrieve the access token with a POST request to https://www.reddit.com/api/v1/access_token, including the following data in your data: grant_type=authorization_code&code=CODE&redirect_uri=URI. Replace CODE with the value you received and URI with your same redirect URI as in the first step.
The response to this third step should return you an access token: store this for future requests on behalf of the user. See https://github.com/reddit-archive/reddit/wiki/OAuth2#retrieving-the-access-token
Extra steps are available and documented for error handling and access token operations (invalidation / renewal).
So, once you've correctly implemented the first step, all you need to do is create an endpoint (the one called when your redirect URI is redirected to) which will :
check the state request param
Retrieve the access token (third step) and store it
Let me know if this is clear enough.

URL not changing on page redirection in Jersey and MongoDB

My scenario is like this:
I'm building a website where I'm posting an ad regarding a topic. So, after the form filling of ad, the request goes to a REST service class as:
http://localhost:8080/cloudproject/postadvaction?title=tution&tag=tution&description=tution+%401000+%2F+month&category=TUTOR&location=indore
Here, the details of ad go in the database which is MongoDB. After all of this is done I'm redirecting to the profile page of user using Viewable model of jersey, where he can see all the ads posted by him. It is done as:
return new Viewable("/profile.jsp");
After this the response is redirected to profile page of the user.
But the problem is that, on redirecting the response to simply profile.jsp, the URL in the address bar has not changed to http://localhost:8080/profile.jsp, instead, it has remained the same as mentioned above. So, when user refreshes the page, the request of same ad post triggers and the whole process is followed again. Since, database is MongoDB, same ad is stored twice in it and same is displayed on the profile page of user with 2 identical ads.
So, how can I redirect to profile page without having the address of servlet in address bar?
Update: The question is related to PRG technique & Duplicate Form Submissions and not to just redirection.
See Post/Redirect/Get
When a web form is submitted to a server through an HTTP POST request, a web user that attempts to refresh the server response in certain user agents can cause the contents of the original HTTP POST request to be resubmitted, possibly causing undesired results, such as a duplicate web purchase.
To avoid this problem, many web developers use the PRG pattern[1] — instead of returning a web page directly, the POST operation returns a redirection command. The HTTP 1.1 specification introduced the HTTP 303 ("See other") response code to ensure that in this situation, the web user's browser can safely refresh the server response without causing the initial HTTP POST request to be resubmitted. However most common commercial applications in use today (new and old alike) still continue to issue HTTP 302 ("Found") responses in these situations.
With Jersey you can use
Response.seeOther(URI) - Create a new ResponseBuilder for a redirection. Used in the redirect-after-POST (aka POST/redirect/GET) pattern.
You just need to change your method signature to return a Response and return the built Response
return Response.seeOther(URI.create(...)).build();
Also stated about the URI parameter
the redirection URI. If a relative URI is supplied it will be converted into an absolute URI by resolving it relative to the base URI of the application (see UriInfo.getBaseUri()).

HtmlUnit: Request website from server in a specific language

I am looking for a clean/simple way in HtmlUnit to request a webpage from a server in a specific language.
To do this i have been trying to request "bankofamerica.com" for their homepage in spanish instead of english.
This is what i have done so far:
I tried to set "Accept-Language" header to "es" in the Http request. I did this using:
myWebClient.addRequestHeader("Accept-Language" , "es");
It did not work. I then created a web request with the following code:
URL myUrl = new URL("https://www.bankofamerica.com/");
WebRequest myRequest = new WebRequest(myUrl);
myRequest.setAdditionalHeader("Accept-Language", "es");
HtmlPage aPage = myWebClient.getPage(myRequest);
Since this failed too i printed out the request object for this url , to check if these headers are being set.
[<url="https://www.bankofamerica.com/", GET, EncodingType[name=application/x-www-form-urlencoded], [], {Accept-Language=es, Accept-Encoding=gzip, deflate, Accept=*/*}, null>]
So the server is being requested for a spanish page but in response its sending the homepage in english (the response header has the value of Content-Language set to en-US)
I did find a hack to retrieve the BOA page in spanish. I visited this page and used the chrome developer tool to get the cookie value from the request
header. I used this value to do the following:
myRequest.setAdditionalHeader("Cookie", "TLTSID= ........._LOCALE_COOKIE=es-US; CONTEXT=es_US; INTL_LANG=es_US; LANG_COOKIE=es_US; hp_pf_anon=anon=((ct=+||st=+||fn=+||zc=+||lang=es_US));..........1870903; throttle_value=43");
I am guessing the answer lies somewhere here.
Here lies my next question. If i am writing a script to retrieve 100 different websites in Spanish (ie Assuming they all have their pages in the spanish) . Is there a clean way in HtmlUnit to accomplish this.
(If cookies is indeed a solution then to create them in htmlunit you need to specify the domain name. One would have to then create cookies for each of the 100 sites. As far as i know there is no way in HtmlUnit to do something like:
Cookie langCookie = new Cookie("All Domains","LANG_COOKIE","es_US");
myWebClient.getCookieManager().addCookie(langCookie);)
NOTE: I am using HtmlUnit 2.12 and setting BrowserVersion.CHROME in the webclient
Thanks.
Regarding your first concern the clear/simple(/only?) way of requesting a webpage in a particular language is, as you said, to set the HTTP Accept-Language request header to the locale(s) you want. That is it.
Now the fact that you request a page in a particular language doesn't mean that you will actually get a page in that language. The server has to be set up to process that HTTP header and respond accordingly. Even if a site has a whole section in spanish it doesn't mean that the site is responding to the HTTP header.
A clear example of this is the page you provided. I performed a quick test on it and found that it is clearly not responding accordingly to the Accept-Language I've set (which was es). Hitting the home page using es resulted in getting results in english. However, the page has a link that states En Español which means In Spanish the page does switch to spanish and you get redirected to https://www.bankofamerica.com?request_locale=es_US.
So you might be tempted to think that the page handles the locale by a request parameter. However, that is not (only) the case. Because if you then open the home page again (without the locale parameter) you will see the Spanish version again. That is clearly a proof that they are being stored somewhere else, most likely in the session, which will most likely be handled by cookies.
That can easily be confirmed by opening a private session or clearing the cookies and confirming this behaviour (I've just done that).
I think that explains the mystery of the webpage existing in Spanish but being fetched in English. (Note how most bank webpages do not conform to basic standards such as responding to simple HTTP requests... and they are handling our money!)
Regarding your second question, it would be like asking What is the recipe to not get ill ever?. It just doesn't depend on you. Also note that your first concerned used the word request while your second concern used the word retrieve. I think it should be clear by now that you can only be 100% sure of what you request but not of what you retrieve.
Regarding setting a value in a cookie manually, that is technically possible. However, that is just like adding another parameter in a get request: http://domain.com?login=yes. The parameter will only be processed by the server if it is expecting it. Otherwise, it will be ignored. That is what will happen to the value in your cookie.
Summary: There are standards to follow. You can try to use them but if the one in the other side doesn't then you won't get the results you expect. Your best choice: do your best and follow the standards.

How to display message after form submit and be idempotent

when a form is submited that inserts a record into the database and the operation was successful, I do a redirect and then pass some parameters in the Url to display the newly inserted record along with a header message (i.e., "Insert was successful").
response.sendRedirect(yPage + "?pid=" + ipd + "&feedback=" + form.getFormFeebackSB() );
I would then display in jsp like:
<c:out value="${param.feedback}" />
I use a redirect instead of a forward because I want the operation to be idempotent. When I used forward users who hit refresh after a successful insert most often always clicked retry on the warning popup and it resulted in duplicate inserts.
Our IT department then discovered that I had a XSS vulnerability:
page.jsp?feedback=%3Cscript%20type=%22text/javascript%22%3Ealert%28%27xss%27%29;%3C/script%3E
So I changed to this:
<c:out value="${param.feedback}" escapeXml='true'/>
but now any <br> in my FeedbackSB get escaped and I end up with a header message as such
Insert was successful<br>An email was sent to Joe<br>Now Complete the XYZ Form;
what is the standard way to pass messages back to user, while keeping any submits idempotent and protecting against XSS?
EDIT:
I searched Flash Scope and came across this http://blog.smartkey.co.uk/2011/01/implementing-flash-scope-in-java-web-applications/
Since my application would require a lot of work to incorporate a framework, the filter mentioned in that link was easy to incorporate and was able to implement flash scope with very little effort.
Don't pass the message itself in a redirect. Store the message under a unique key in the session, redirect with the key of this message as URL parameter, then go to the session, get the message, and display it.
I would also remove the message from the session immediately: if the user refreshes, there is no reason to tell him again that the insert was successful.
Most of the MVC frameworks do that for you, using what they usually call a Flash scope (session attributes that are removed from the session as soon as they've been retrieved).

Redirect to servlet fails

I have a servlet named EditPhotos which, believe it or not, is used for editing the photos associated with a certain item on a web design I am developing. The URL path to edit a photo is [[SITEROOT]]/EditPhotos/[[ITEMNAME]].
When you go to this path (GET), the page loads fine. You can then click on a 'delete' link that POSTs to the same page, telling it to delete the photo. The servlet receives this delete command properly and successfully deletes the photo. It then sends a redirect back to the first page (GET).
For some reason, this redirect fails. I don't know how or why, but using the HTTPFox plugin for firefox, I see that the POST request receives 0 bytes in response and has the code NS_BINDING_ABORTED.
The code I am using to send the redirect, is the same code I have used throughout the website to send redirects:
response.sendRedirect(Constants.SITE_ROOT + "EditPhotos/" + itemURL);
I have checked the final URL that the redirect sends, and it is definitely correct, but the browser never receives the redirect. Why?
Read the server logs. Do you see IllegalStateException: response already committed with the sendRedirect() call in the trace?
If so, then that means that the redirect failed because the response headers are already been sent. Ensure that you aren't touching the HttpServletResponse at all before calling the sendRedirect(). A redirect namely exist of basically a Location response header with the new URL as value.
If not, then you're probably handling the request using JavaScript which in turn failed to handle the new location.
If neither is the case or you still cannot figure it, then we'd be interested in the smallest possible copy'n'pasteable code snippet which reproduces exactly this problem. Update then your question to include it.
Update as per the comments, the culprit is indeed in JavaScript. A redirect on a XMLHttpRequest POST isn't going to work. Are you using homegrown XMLHttpRequest functions or a library around it like as jQuery? If jQuery, please read this question carefully. It boils down to that you need to return a specific response and then let JS/jQuery do the new window.location itself.
Turns out that it was the JavaScript I was using to send the POST that was the problem.
I originally had this:
Delete
And everything got fixed when I changed it to this:
Delete
The deletePhoto function is:
function deletePhoto(photoID) {
doPost(document.URL, {'action':'delete', 'id':photoID});
}
function doPost(path, params) {
var form = document.createElement("form");
form.setAttribute("method", "POST");
form.setAttribute("action", path);
for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form.submit();
}

Categories

Resources