Pinned file upload in Groovy

I need to get a file in memory in my application from a secure website. I have the url of the file to capture, but it cannot solve the security problem. Here is the code from the cookbook sample page :

def download(address) { def file = new FileOutputStream(address.tokenize("/")[-1]) def out = new BufferedOutputStream(file) out << new URL(address).openStream() out.close() } 

and here is my "memory" version of the same function, which should return an array of bytes of the contents of the file:

 def downloadIntoMem(address) { // btw, how frickin powerful is Groovy to do this in 3 lines (or less) def out = new ByteArrayOutputStream() out << new URL(address).openStream() out.toByteArray() } 

When I try to do this against an insecure URL (select any image file that you can find on the network), it works fine. However, if I choose a URL that requires a user / password, do not leave.

Ok, a little work on this. Authenticator seems to work , but round. The first time I access the URL, I get a 302 response indicating the location on the login server. If I access this location using the Authenticator set, then I get another 302 with a cookie and a place set to the original URL. If I access the original, the download is working correctly.

So, I need to manipulate the browser a bit, but in the end it all works.

The creation of this community wiki, so others may add other methods.

Thanks!

+3
source share
2 answers

If creds on url does not work, you can use this. It works for basic authentication.

 new File(localPath).withOutputStream { out -> def url = new URL(remoteUrl).openConnection() def remoteAuth = "Basic " + "${user}:${passwd}".bytes.encodeBase64() url.setRequestProperty("Authorization", remoteAuth); out << url.inputStream } 

Hope this helps!

+10
source

Depending on the type of authorization for the server, you can put credit resources into it:

 def address = "http://admin: sekr1t@myhost.com " def url = new URL(address) assert "admin:sekr1t" == url.userInfo 

If you do not go through the proxy server, you do not want to use the proxy server you are talking about. This is not applicable.

+3
source

All Articles