I am reading here
http://groovy.codehaus.org/modules/http-builder/doc/handlers.html
"In cases where a response sends a redirect status code, this is handled internally by Apache HttpClient, which by default will simply follow the redirect by re-sending the request to the new URL. You do not need to do anything special in order to follow 302 responses."
This seems to work fine when I simply use the get() or post() methods without a closure.
However, when I use a closure, I seem to lose 302 handling. Is there some way I can handle this myself? Thank you
p.s. Here is my log output showing it is a 302 response
[java] FINER: resp.statusLine: "HTTP/1.1 302 Found"
Here is the relevant code:
// Copyright (C) 2010 Misha Koshelev. All Rights Reserved.
package com.mksoft.fbbday.main
import groovyx.net.http.ContentType
import java.util.logging.Level
import java.util.logging.Logger
class HTTPBuilder {
def dataDirectory
HTTPBuilder(dataDirectory) {
this.dataDirectory=dataDirectory
}
// Main logic
def logger=Logger.getLogger(this.class.name)
def closure={resp,reader->
logger.finer("resp.statusLine: \"${resp.statusLine}\"")
if (logger.isLoggable(Level.FINEST)) {
def respHeadersString='Headers:';
resp.headers.each() { header->respHeadersString+="\n\t${header.name}=\"${header.value}\"" }
logger.finest(respHeadersString)
}
def text=reader.text
def lastHtml=new File("${dataDirectory}${File.separator}last.html")
if (lastHtml.exists()) {
lastHtml.delete()
}
lastHtml<<text
new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(text)
}
def processArgs(args) {
if (logger.isLoggable(Level.FINER)) {
def argsString='Args:';
args.each() { arg->argsString+="\n\t${arg.key}=\"${arg.value}\"" }
logger.finer(argsString)
}
args.contentType=groovyx.net.http.ContentType.TEXT
args
}
// HTTPBuilder methods
def httpBuilder=new groovyx.net.http.HTTPBuilder ()
def get(args) {
httpBuilder.get(processArgs(args),closure)
}
def post(args) {
args.contentType=groovyx.net.http.ContentType.TEXT
httpBuilder.post(processArgs(args),closure)
}
}
Here is a specific tester:
#!/usr/bin/env groovy
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import static groovyx.net.http.ContentType.URLENC
import java.util.logging.ConsoleHandler
import java.util.logging.Level
import java.util.logging.Logger
// MUST ENTER VALID FACEBOOK EMAIL AND PASSWORD BELOW !!!
def email=''
def pass=''
// Remove default loggers
def logger=Logger.getLogger('')
def handlers=logger.handlers
handlers.each() { handler->logger.removeHandler(handler) }
// Log ALL to Console
logger.setLevel Level.ALL
def consoleHandler=new ConsoleHandler()
consoleHandler.setLevel Level.ALL
logger.addHandler(consoleHandler)
// Facebook - need to get main page to capture cookies
def http = new HTTPBuilder()
http.get(uri:'http://www.facebook.com')
// Login
def html=http.post(uri:'https://login.facebook.com/login.php?login_attempt=1',body:[email:email,pass:pass])
assert html==null
// Why null?
html=http.post(uri:'https://login.facebook.com/login.php?login_attempt=1',body:[email:email,pass:pass]) { resp,reader->
assert resp.statusLine.statusCode==302
// Shouldn't we be redirected???
// http://groovy.codehaus.org/modules/http-builder/doc/handlers.html
// "In cases where a response sends a redirect status code, this is handled internally by Apache HttpClient, which by default will simply follow the redirect by re-sending the request to the new URL. You do not need to do anything special in order to follow 302 responses. "
}
Here are relevant logs:
FINE: Receiving response: HTTP/1.1 302 Found
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << HTTP/1.1 302 Found
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Expires: Sat, 01 Jan 2000 00:00:00 GMT
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Location: http://www.facebook.com/home.php?
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << P3P: CP="DSP LAW"
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Pragma: no-cache
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Set-Cookie: datr=1275687438-9ff6ae60a89d444d0fd9917abf56e085d370277a6e9ed50c1ba79; expires=Sun, 03-Jun-2012 21:37:24 GMT; path=/; domain=.facebook.com
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Set-Cookie: lxe=koshelev%40post.harvard.edu; expires=Tue, 28-Sep-2010 15:24:04 GMT; path=/; domain=.facebook.com; httponly
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Set-Cookie: lxr=deleted; expires=Thu, 04-Jun-2009 21:37:23 GMT; path=/; domain=.facebook.com; httponly
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Set-Cookie: pk=183883c0a9afab1608e95d59164cc7dd; path=/; domain=.facebook.com; httponly
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Content-Type: text/html; charset=utf-8
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << X-Cnection: close
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Date: Fri, 04 Jun 2010 21:37:24 GMT
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader
FINE: << Content-Length: 0
Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies
FINE: Cookie accepted: "[version: 0][name: datr][value: 1275687438-9ff6ae60a89d444d0fd9917abf56e085d370277a6e9ed50c1ba79][domain: .facebook.com][path: /][expiry: Sun Jun 03 16:37:24 CDT 2012]".
Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies
FINE: Cookie accepted: "[version: 0][name: lxe][value: koshelev%40post.harvard.edu][domain: .facebook.com][path: /][expiry: Tue Sep 28 10:24:04 CDT 2010]".
Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies
FINE: Cookie accepted: "[version: 0][name: lxr][value: deleted][domain: .facebook.com][path: /][expiry: Thu Jun 04 16:37:23 CDT 2009]".
Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies
FINE: Cookie accepted: "[version: 0][name: pk][value: 183883c0a9afab1608e95d59164cc7dd][domain: .facebook.com][path: /][expiry: null]".
Jun 4, 2010 4:37:22 PM org.apache.http.impl.client.DefaultRequestDirector execute
FINE: Connection can be kept alive indefinitely
Jun 4, 2010 4:37:22 PM groovyx.net.http.HTTPBuilder doRequest
FINE: Response code: 302; found handler: post302$_run_closure2#7023d08b
Jun 4, 2010 4:37:22 PM groovyx.net.http.HTTPBuilder doRequest
FINEST: response handler result: null
Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.SingleClientConnManager releaseConnection
FINE: Releasing connection org.apache.http.impl.conn.SingleClientConnManager$ConnAdapter#605b28c9
You can see there is clearly a location argument.
Thank you
Misha
I've had the same problem with HTTPBuilder until I realized that the HTTP/1.1 spec states:
Redirection 3xx
[..]
This class of status code indicates
that further action needs to be
taken by the user agent in order to
fulfill the request. The action
required MAY be carried out by the
user agent without interaction with
the user if and only if the method
used in the second request is GET
or HEAD.
302 Found
[..]
If the 302 status code is received in response to a request other
than GET or HEAD, the user agent MUST NOT automatically redirect the
request unless it can be confirmed by the user, since this might
change the conditions under which the request was issued.
Essentially this means that the request following a POST and 302 redirect won't work automatically and will require user intervention if the HTTP/1.1 spec is followed by the letter. Not all Http clients follow this practice, in fact most browsers do not. However the Apache Http Client (which is the underlying Http client for HttpBuilder) is spec compliant. There is an issue in the Apache Http Client bugtracker that contains more information and a possible solution for the problem.
void test_myPage_shouldRedirectToLogin() {
def baseURI = "http://servername"
def httpBuilder = new HTTPBuilder(baseURI)
// Make sure that HttpClient doesn't perform a redirect
def dontHandleRedirectStrategy = [
getRedirect : { request, response, context -> null},
isRedirected : { request, response, context -> false}
]
httpBuilder.client.setRedirectStrategy(dontHandleRedirectStrategy as RedirectStrategy)
// Execute a GET request and expect a redirect
httpBuilder.request(Method.GET, ContentType.TEXT) {
req ->
uri.path = '/webapp/de/de/myPage'
response.success = { response, reader ->
assertThat response.statusLine.statusCode, is(302)
assertThat response.headers['Location'].value, startsWith("${baseURI}/webapp/login")
}
response.failure = { response, reader ->
fail("Expected redirect but received ${response.statusLine} \n ${reader}")
}
}
}
302 status coming because, after action on any link redirected url not follow by HttpBuilder so we need to add "RedirectStrategy" explicitly.
What other headers do you see when you process the 302 response? If you were to turn on http client logging you'd expect to see HttpClient process the 302 response and automatically request URL in the Location header. What do you see when you process that URL? Does it work for any URL?
Try http://www.sun.com (it redirects to Oracle now.) I'm just wondering if the server you're working with is doing something wonky like sending a 302 with no Location header.
Related
When I send requests at the same time I receive 401. What could be wrong?
Request URL: http://localhost:5000/api/***
Request Method: PUT
Status Code: 401
Date: Mon, 01 Nov 2021 23:20:08 GMT
Cookie: JSESSIONID=D0A23516553FAA68121D9013A986D62C
Request URL: http://localhost:5000/api/***
Request Method: PUT
Status Code: 401
Date: Mon, 01 Nov 2021 23:20:08 GMT
Cookie: JSESSIONID=D0A23516553FAA68121D9013A986D62C
getting this error after hibernate outputs the data, any idea why this would be happening. please help!
Sep 07, 2016 12:07:00 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:postgresql://localhost:5432/bendb]
Sep 07, 2016 12:07:00 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 3 * Server responded with a response on thread http-nio-8080-exec-5
3 < 200
3 < Access-Control-Allow-Methods: GET, POST, DELETE, PUT
3 < Access-Control-Allow-Origin: *
3 < Allow: OPTIONS
3 < Content-Type: application/json
Sep 07, 2016 12:07:00 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 4 * Server responded with a response on thread http-nio-8080-exec-5
4 < 500
Sorry found a bug in my code so apparently the code change i made was trying to map all the junction tables (collections) in that get user rest call hence jersey just breaks out while attempting to do that. un Commenting that code and just passing the normal data sets solved the issue.
I want to load photourl from buffer if no change, but it works only after first refresh of page. When I open page for first time this is my response
Cache-Control no-cache
Content-Length 12279
Content-Type text/plain
Date Thu, 18 Aug 2016 10:26:45 GMT
Expires Mon, 01 Jan 1990 00:00:00 GMT
Last-Modified Thu, 18 Aug 2016 09:56:55 GMT
Server Development/1.0
after refresh i have 304 status and response:
Cache-Control no-cache, no-store, max-age=0, must-revalidate
Date Thu, 18 Aug 2016 10:29:21 GMT
Expires 0
Last-Modified Thu, 18 Aug 2016 09:56:55 GMT
Pragma no-cache
Server Development/1.0
X-Frame-Options DENY
X-XSS-Protection 1; mode=block
x-content-type-options nosniff
and in request
If-Modified-Since Thu, 18 Aug 2016 09:56:55 GMT
after another refresh i have 200 status like on first visit and data are reloaded from server.
This is my controller.
#ResponseBody
#RequestMapping(value = "/photo", produces = "text/plain", method = RequestMethod.GET)
public String myPhoto(HttpServletResponse response, WebRequest request) {
Photo photo = photoService.getPhoto();
long lastModified = photo.getModificationDate().getTime();
if (request.checkNotModified(lastModified)) {
return null;
}
return photo.photoURL();
}
So, I have followed the tutorial for implementing simple login page over here https://varuntayur.wordpress.com/2012/01/25/session-management-in-gwt/
I tried communicating on the page itself, the author has been very helpful, but up to certain point.
The code is pretty long, so I've uploaded it here:
http://1drv.ms/1GZQqFV
Please be so kind to check it out.
The error displayed is the following:
[WARN] 404 - POST /atlas_emergency_status_page/LoginService (127.0.0.1) 1405 bytes
Request headers
Host: 127.0.0.1:8888
Connection: keep-alive
Content-Length: 200
X-GWT-Module-Base: http://127.0.0.1:8888/atlas_emergency_status_page/
X-GWT-Permutation: 512BC5E71D8D41DD923CAA7193842B68
Origin: http://127.0.0.1:8888
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Content-Type: text/x-gwt-rpc; charset=UTF-8
Accept: */*
Referer: http://127.0.0.1:8888/ATLAS_Emergency_Status_Page.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,fr-CH;q=0.6,fr;q=0.4,ka;q=0.2,ru;q=0.2
Response headers
Content-Type: text/html;charset=ISO-8859-1
Cache-Control: must-revalidate,no-cache,no-store
Content-Length: 1405
EDIT
I heva found the error, in web.xml I mapped servlet as LoginServiceImpl, had to be LoginService.
But now, I have another problem, on clicking the login button, nothing happens and no error is displayed, which is even worse...
What could be the problem?
EDIT 2
I have added the logger to be able to better understand what's happening.
Here is the output of logger:
Wed Nov 04 17:11:44 GMT+100 2015 logger1 INFO: enbl = false
Wed Nov 04 17:11:44 GMT+100 2015 logger1 INFO: enbl = false
Wed Nov 04 17:11:44 GMT+100 2015 logger1 INFO: No sessionID
Wed Nov 04 17:11:46 GMT+100 2015 logger1 INFO: Called login
Wed Nov 04 17:11:46 GMT+100 2015 logger1 INFO: Configured login dialog box
Wed Nov 04 17:11:47 GMT+100 2015 logger1 INFO: username: password:
Wed Nov 04 17:11:47 GMT+100 2015 logger1 INFO: Success
Wed Nov 04 17:11:47 GMT+100 2015 com.google.gwt.logging.client.LogConfiguration SEVERE: (TypeError) __gwt$exception: <skipped>: Cannot read property 'allowNestedValues' of nullcom.google.gwt.core.client.JavaScriptException: (TypeError) __gwt$exception: <skipped>: Cannot read property 'allowNestedValues' of null
at Unknown.$get(atlas_emergency_status_page-0.js#18:2152)
at Unknown.$getLoggedIn(atlas_emergency_status_page-0.js#36:2227)
at Unknown.$onSuccess_0(atlas_emergency_status_page-0.js#88:1182)
at Unknown.onSuccess_0(atlas_emergency_status_page-0.js#3:1213)
at Unknown.onResponseReceived(atlas_emergency_status_page-0.js#34:15260)
at Unknown.$fireOnResponseReceived(atlas_emergency_status_page-0.js#14:7513)
at Unknown.onReadyStateChange(atlas_emergency_status_page-0.js#5:7718)
at Unknown.<anonymous>(atlas_emergency_status_page-0.js#13:18406)
at Unknown.apply_0(atlas_emergency_status_page-0.js#23:3688)
at Unknown.entry0(atlas_emergency_status_page-0.js#16:3755)
It seems to go into error after calling
public void onSuccess(UserDTO result) {
logger.log(Level.INFO, "Success");
and somewhere on this line I would say...
logger.log(Level.INFO, "username from UserDTO: " + result.getName());
if (result.getLoggedIn()) {
Again, sorry for newbie questions, but this is way over my level...
I'm trying to use the Java API to upload large files, but I need to also add user metadata. If I just use
TransferManager tm = new TransferManager(new BasicAWSCredentials(accessKey, secretKey));
Upload upload = tm.upload(AmazonS3Manager.bucketName, imageKey, file);
upload.waitForCompletion();
Then everything works fine, but if I use:
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(file.length());
metadata.addUserMetadata("My key", "My value");
FileInputStream input = new FileInputStream(file);
Upload upload = tm.upload(AmazonS3Manager.bucketName, imageKey, input, metadata);
Then it doesn't work, and I get the following output in the console:
Jul 5, 2011 4:33:15 PM com.amazonaws.http.AmazonHttpClient executeHelper
INFO: Sending Request: POST https://mybucket.s3.amazonaws.com /test.jpg Parameters: (uploads: null, ) Headers: (Content-Type: application/x-www-form-urlencoded; charset=utf-8, x-amz-meta-length: 312612077, )
Jul 5, 2011 4:33:16 PM com.amazonaws.http.AmazonHttpClient handleResponse
INFO: Received successful response: 200, AWS Request ID: 2A5B3538795CE730
Jul 5, 2011 4:33:16 PM com.amazonaws.http.AmazonHttpClient executeHelper
INFO: Sending Request: PUT https://mybucket.s3.amazonaws.com /test.jpg Parameters: (uploadId: rwUlbXqtRyMUWiVYKzGqRQH90fVLi9_|Secret Key Removed|_w--, partNumber: 1, ) Headers: (Content-Length: 5242880, Content-Type: application/x-www-form-urlencoded; charset=utf-8, )
Jul 5, 2011 4:34:00 PM com.amazonaws.http.AmazonHttpClient handleResponse
INFO: Received successful response: 200, AWS Request ID: 5E5AF291FBDBDD36
Jul 5, 2011 4:34:00 PM com.amazonaws.http.AmazonHttpClient executeHelper
INFO: Sending Request: PUT https://mybucket.s3.amazonaws.com /test.jpg Parameters: (uploadId: rwUlbXqtRyMUWiVYKzGqRQH90fVLi9_|Secret Key Removed|_w--, partNumber: 2, ) Headers: (Content-Length: 5242880, Content-Type: application/x-www-form-urlencoded; charset=utf-8, )
Jul 5, 2011 4:34:00 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: I/O exception (java.io.IOException) caught when processing request: Read error
Jul 5, 2011 4:34:00 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: Retrying request
Jul 5, 2011 4:34:00 PM com.amazonaws.http.AmazonHttpClient executeHelper
WARNING: Unable to execute HTTP request: null
Jul 5, 2011 4:34:00 PM com.amazonaws.http.AmazonHttpClient executeHelper
INFO: Sending Request: DELETE https://mybucket.s3.amazonaws.com /test.jpg Parameters: (uploadId: rwUlbXqtRyMUWiVYKzGqRQH90fVLi9_|Secret Key Removed|_w--, ) Headers: (Content-Type: application/x-www-form-urlencoded; charset=utf-8, )
Jul 5, 2011 4:34:01 PM com.amazonaws.http.AmazonHttpClient handleResponse
INFO: Received successful response: 204, AWS Request ID: 0EFC3F8D0FA6097E
Any help greatly appreciated!
You may also need to set content type and, possibly, checksum as it can't be determined from input stream. This has some information for similar situation http://docs.amazonwebservices.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/AmazonS3.html#putObject(com.amazonaws.services.s3.model.PutObjectRequest)
If you are trying to upload more than 5 GB file with updating metadata then amazon not allowing to do so. Because amazon s3 not providing copy operation for more then 5Gb file.
Amazon S3 recently started to support copy operation wtih multipart operation so for that i can not say you something yet.
https://forums.aws.amazon.com/thread.jspa?messageID=256605𾩝
Thanks
You can use following code for your file upload:
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(file.length());
metadata.addUserMetadata("My key", "My value");
FileInputStream input = new FileInputStream(file);
PutObjectRequest putObjectRequest = new PutObjectRequest(AmazonS3Manager.bucketName, imageKey, input, metadata);
s3client.putObject(putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead));
Thanks