I am creating a program that will download a .jar (java) file from a web server, by reading the URL that is specified in the .jad file of the same game/application. I’m using Python 3.2.1
I’ve managed to extract the URL of the JAR file from the JAD file (every JAD file contains the URL to the JAR file), but as you may imagine, the extracted value is type() string.
Here’s the relevant function:
def downloadFile(URL=None):
import httplib2
h = httplib2.Http(".cache")
resp, content = h.request(URL, "GET")
return content
downloadFile(URL_from_file)
However I always get an error saying that the type in the function above has to be bytes, and not string. I’ve tried using the URL.encode(‘utf-8′), and also bytes(URL,encoding=’utf-8’), but I’d always get the same or similar error.
So basically my question is how to download a file from a server when the URL is stored in a string type?
If you want to obtain the contents of a web page into a variable, just
readthe response ofurllib.request.urlopen:The easiest way to download and save a file is to use the
urllib.request.urlretrievefunction:But keep in mind that
urlretrieveis considered legacy and might become deprecated (not sure why, though).So the most correct way to do this would be to use the
urllib.request.urlopenfunction to return a file-like object that represents an HTTP response and copy it to a real file usingshutil.copyfileobj.If this seems too complicated, you may want to go simpler and store the whole download in a
bytesobject and then write it to a file. But this works well only for small files.It is possible to extract
.gz(and maybe other formats) compressed data on the fly, but such an operation probably requires the HTTP server to support random access to the file.