Urllib2 httperror http error 501 https required

As of January 15, 2020 I am receiving the following responses upon making requests to The Central Repository: Requests to http://repo1.maven.org/maven2/ return a 501 HTTPS Required status and a bo...

As of January 15, 2020 I am receiving the following responses upon making requests to The Central Repository:

Requests to http://repo1.maven.org/maven2/ return a 501 HTTPS Required status and a body:

501 HTTPS Required. 
Use https://repo1.maven.org/maven2/
More information at https://links.sonatype.com/central/501-https-required
Requests to http://repo.maven.apache.org/maven2/ return a 501 HTTPS Required status and a body:

501 HTTPS Required. 
Use https://repo.maven.apache.org/maven2/
More information at https://links.sonatype.com/central/501-https-required

How do I satisfy this requirement so that I can regain access to Central?

I got this error in the console

    [INFO] Scanning for projects...
    [INFO] 
    [INFO] ----------------------------<  >----------------------------
    [INFO] Building demo 0.0.1-SNAPSHOT
    [INFO] --------------------------------[ jar ]---------------------------------
    [INFO] Downloading from : http://repo1.maven.org/maven2/org/mongodb/mongo-java-driver/3.12.0/mongo-java-driver-3.12.0.pom
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  11.136 s
    [INFO] Finished at: 2020-01-16T15:27:53+05:30
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal on project demo: Could not resolve dependencies for project com.tcs:demo:jar:0.0.1-SNAPSHOT: Failed to collect dependencies at org.mongodb:mongo-java-driver:jar:3.12.0: Failed to read artifact descriptor for org.mongodb:mongo-java-driver:jar:3.12.0: Could not transfer artifact org.mongodb:mongo-java-driver:pom:3.12.0 from/to central (http://repo1.maven.org/maven2/): Failed to transfer http://repo1.maven.org/maven2/org/mongodb/mongo-java-driver/3.12.0/mongo-java-driver-3.12.0.pom. Error code 501, HTTPS Required -> [Help 1]
    [ERROR] 
    [ERROR] To see the full stack trace ``of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR] 
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

And using site plugin:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-site-plugin:2.2:site (default-site) on project my-proj: SiteToolException: The site descriptor cannot be resolved from the repository: ArtifactResolutionException: Unable to locate site descriptor: Could not transfer artifact org.x.y:name:xml:site_en:3.5.1.b550 from/to central (http://repo1.maven.org/maven2): Transfer failed for http://repo1.maven.org/maven2/org/x/y/3.5.1.b550/name-3.5.1.b550-site_en.xml 501 HTTPS Required

rogerdpack's user avatar

rogerdpack

60.5k35 gold badges259 silver badges379 bronze badges

asked Jan 16, 2020 at 7:24

Giriraj's user avatar

0

I fixed with the following steps but it uses http:
1) got to .m2 folder
2) create file settings.xml
3) copy paste below

<settings>
    <mirrors>
        <mirror>
          <id>centralhttps</id>
          <mirrorOf>central</mirrorOf>
          <name>Maven central https</name>
          <url>http://insecure.repo1.maven.org/maven2/</url>
        </mirror>
      </mirrors>
      </settings>

answered Jan 27, 2020 at 18:08

Person's user avatar

PersonPerson

6014 silver badges4 bronze badges

3

Try to add the next statament in your pom.xml

<pluginRepositories>
<pluginRepository>
  <id>central</id>
  <name>Central Repository</name>
  <url>https://repo.maven.apache.org/maven2</url>
  <layout>default</layout>
  <snapshots>
    <enabled>false</enabled>
  </snapshots>
  <releases>
    <updatePolicy>never</updatePolicy>
  </releases>
</pluginRepository>
</pluginRepositories>

<repositories>
 <repository>
   <id>central</id>
   <name>Central Repository</name>
   <url>https://repo.maven.apache.org/maven2</url>
   <layout>default</layout>
   <snapshots>
      <enabled>false</enabled>
   </snapshots>
 </repository>
</repositories>

Also, you have to specified the repositories in: MAVENconfsettings.xml

<mirrors>
 <mirror>
   <id>other-mirror</id>
   <mirrorOf>central</mirrorOf>
   <name>Other Mirror Repository</name>
   <url>http://insecure.repo1.maven.org/maven2/</url>
 </mirror>
 <mirror>
  <id>internal-repository</id>
  <name>Maven Repository Manager running on https://repo1.maven.org/maven2</name>
  <url>https://repo1.maven.org/maven2</url>
  <mirrorOf>*</mirrorOf>
 </mirror>
</mirrors>

answered Jan 23, 2020 at 20:50

Carlos Ruiz de la Vega's user avatar

Beware that your parent pom can (re) define repositories as well, and if it has overridden central and specified http for whatever reason, you’ll need to fix that (so places to fix: ~/.m2/settings.xml
AND also parent poms).

If you can’t fix it in parent pom, you can override parent pom’s repo’s, like this, in your child pom (extracted from the 3.6.3 default super pom, seems they changed the name from repo1 as well):

  <repositories>
    <repository>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url> <!-- the https you've been looking for -->
      <layout>default</layout>
      <snapshots>
        <enabled>false</enabled> <!-- or set to false if desired, default is true https://stackoverflow.com/a/61684539/32453 -->
      </snapshots>
    </repository>
  </repositories>

answered Jan 18, 2020 at 0:05

rogerdpack's user avatar

rogerdpackrogerdpack

60.5k35 gold badges259 silver badges379 bronze badges

FYI for Gradle users just use,

repositories {
   maven {
      url = 'https://repo.maven.apache.org/maven2'
   }
} 

answered Jan 28, 2020 at 0:40

Panduka DeSilva's user avatar

Martin, thanks for elaborating my thoughts!

I have dug I bit deeper in Python2's urllib code with pdb, and I think I have narrowed the issue down to what open_http does.

In my example code, replacing opener.open(url) with opener.open_http(url) gives the same problem.

I realize I did not provide you with the output of the script, so here it is:

* Python 2.7.10

python urllib_error.py
('Trying to open', 'https://www.python.org')
Traceback (most recent call last):
  File "urllib_error.py", line 30, in <module>
    opener.open_http((host, selector))
  File "/home/mazzucco/.pyenv/versions/2.7.10/lib/python2.7/urllib.py", line 364, in open_http
    return self.http_error(url, fp, errcode, errmsg, headers)
  File "/home/mazzucco/.pyenv/versions/2.7.10/lib/python2.7/urllib.py", line 381, in http_error
    return self.http_error_default(url, fp, errcode, errmsg, headers)
  File "/home/mazzucco/.pyenv/versions/2.7.10/lib/python2.7/urllib.py", line 386, in http_error_default
    raise IOError, ('http error', errcode, errmsg, headers)
IOError: ('http error', 501, 'Not Implemented', <httplib.HTTPMessage instance at 0x7f875a67b950>)

* Python 3.4.3

python urllib_error.py
Trying to open https://www.python.org
Traceback (most recent call last):
  File "urllib_error.py", line 30, in <module>
    opener.open_http((host, selector))
  File "/home/mazzucco/.pyenv/versions/3.4.3/lib/python3.4/urllib/request.py", line 1805, in open_http
    return self._open_generic_http(http.client.HTTPConnection, url, data)
  File "/home/mazzucco/.pyenv/versions/3.4.3/lib/python3.4/urllib/request.py", line 1801, in _open_generic_http
    response.status, response.reason, response.msg, data)
  File "/home/mazzucco/.pyenv/versions/3.4.3/lib/python3.4/urllib/request.py", line 1821, in http_error
    return self.http_error_default(url, fp, errcode, errmsg, headers)
  File "/home/mazzucco/.pyenv/versions/3.4.3/lib/python3.4/urllib/request.py", line 1826, in http_error_default
    raise HTTPError(url, errcode, errmsg, headers, None)
urllib.error.HTTPError: HTTP Error 501: Not Implemented

When I unwrap the contents of httplib.HTTPMessage, the error page returned by the squid proxy says:

-------------------------------------------------------
ERROR
The requested URL could not be retrieved

The following error was encountered while trying to retrieve the URL: https://www.python.org

    Unsupported Request Method and Protocol

Squid does not support all request methods for all access protocols. For example, you can not POST a Gopher request.
-------------------------------------------------------

Looking at Python2's implementation of URLopener's open_http, I can get an even more minimal failing example limited to httplib:


import httplib

host = 'proxy.corp.com:8181'  # this is not the actual proxy

selector = 'https://www.python.org'

print("Trying to open", selector)

h = httplib.HTTP(host)
h.putrequest('GET', selector)
h.putheader('User-Agent', 'Python-urllib/1.17')
h.endheaders(None)
errcode, errmsg, headers = h.getreply()

print(errcode, errmsg)
print(headers.items())


Running the script on Python 2.7.10 prints:

('Trying to open', 'https://www.python.org')
(501, 'Not Implemented')
[('content-length', '3069'), ('via', '1.0 proxy.corp.com (squid/3.1.6)'), ('x-cache', 'MISS from proxy.corp.com'), ('content-language', 'en'), ('x-squid-error', 'ERR_UNSUP_REQ 0'), ('x-cache-lookup', 'NONE from proxy.corp.com:8181'), ('vary', 'Accept-Language'), ('server', 'squid/3.1.6'), ('proxy-connection', 'close'), ('date', 'Fri, 10 Jul 2015 09:27:14 GMT'), ('content-type', 'text/html'), ('mime-version', '1.0')]


As I said, I found out about this when using buildout to download files over HTTPS.

Buildout uses urllib.urlretrieve on Python2 and urllib.request.urlretrieve on Python3. I guess that the latter has been fixed in issue 1424152, so that's why I can download with buildout on Python3.
Author: Michael Foord

Introduction¶

urllib.request is a Python module for fetching URLs
(Uniform Resource Locators). It offers a very simple interface, in the form of
the urlopen function. This is capable of fetching URLs using a variety of
different protocols. It also offers a slightly more complex interface for
handling common situations — like basic authentication, cookies, proxies and so
on. These are provided by objects called handlers and openers.

urllib.request supports fetching URLs for many “URL schemes” (identified by the string
before the ":" in URL — for example "ftp" is the URL scheme of
"ftp://python.org/") using their associated network protocols (e.g. FTP, HTTP).
This tutorial focuses on the most common case, HTTP.

For straightforward situations urlopen is very easy to use. But as soon as you
encounter errors or non-trivial cases when opening HTTP URLs, you will need some
understanding of the HyperText Transfer Protocol. The most comprehensive and
authoritative reference to HTTP is RFC 2616. This is a technical document and
not intended to be easy to read. This HOWTO aims to illustrate using urllib,
with enough detail about HTTP to help you through. It is not intended to replace
the urllib.request docs, but is supplementary to them.

Fetching URLs¶

The simplest way to use urllib.request is as follows:

import urllib.request
with urllib.request.urlopen('http://python.org/') as response:
   html = response.read()

If you wish to retrieve a resource via URL and store it in a temporary location,
you can do so via the urlretrieve() function:

import urllib.request
local_filename, headers = urllib.request.urlretrieve('http://python.org/')
html = open(local_filename)

Many uses of urllib will be that simple (note that instead of an ‘http:’ URL we
could have used a URL starting with ‘ftp:’, ‘file:’, etc.). However, it’s the
purpose of this tutorial to explain the more complicated cases, concentrating on
HTTP.

HTTP is based on requests and responses — the client makes requests and servers
send responses. urllib.request mirrors this with a Request object which represents
the HTTP request you are making. In its simplest form you create a Request
object that specifies the URL you want to fetch. Calling urlopen with this
Request object returns a response object for the URL requested. This response is
a file-like object, which means you can for example call .read() on the
response:

import urllib.request

req = urllib.request.Request('http://www.voidspace.org.uk')
with urllib.request.urlopen(req) as response:
   the_page = response.read()

Note that urllib.request makes use of the same Request interface to handle all URL
schemes. For example, you can make an FTP request like so:

req = urllib.request.Request('ftp://example.com/')

In the case of HTTP, there are two extra things that Request objects allow you
to do: First, you can pass data to be sent to the server. Second, you can pass
extra information (“metadata”) about the data or the about request itself, to
the server — this information is sent as HTTP “headers”. Let’s look at each of
these in turn.

Data¶

Sometimes you want to send data to a URL (often the URL will refer to a CGI
(Common Gateway Interface) script or other web application). With HTTP,
this is often done using what’s known as a POST request. This is often what
your browser does when you submit a HTML form that you filled in on the web. Not
all POSTs have to come from forms: you can use a POST to transmit arbitrary data
to your own application. In the common case of HTML forms, the data needs to be
encoded in a standard way, and then passed to the Request object as the data
argument. The encoding is done using a function from the urllib.parse
library.

import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }

data = urllib.parse.urlencode(values)
data = data.encode('ascii') # data should be bytes
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
   the_page = response.read()

Note that other encodings are sometimes required (e.g. for file upload from HTML
forms — see HTML Specification, Form Submission for more
details).

If you do not pass the data argument, urllib uses a GET request. One
way in which GET and POST requests differ is that POST requests often have
“side-effects”: they change the state of the system in some way (for example by
placing an order with the website for a hundredweight of tinned spam to be
delivered to your door). Though the HTTP standard makes it clear that POSTs are
intended to always cause side-effects, and GET requests never to cause
side-effects, nothing prevents a GET request from having side-effects, nor a
POST requests from having no side-effects. Data can also be passed in an HTTP
GET request by encoding it in the URL itself.

This is done as follows:

>>> import urllib.request
>>> import urllib.parse
>>> data = {}
>>> data['name'] = 'Somebody Here'
>>> data['location'] = 'Northampton'
>>> data['language'] = 'Python'
>>> url_values = urllib.parse.urlencode(data)
>>> print(url_values)  # The order may differ from below.  
name=Somebody+Here&language=Python&location=Northampton
>>> url = 'http://www.example.com/example.cgi'
>>> full_url = url + '?' + url_values
>>> data = urllib.request.urlopen(full_url)

Notice that the full URL is created by adding a ? to the URL, followed by
the encoded values.

Handling Exceptions¶

urlopen raises URLError when it cannot handle a response (though as
usual with Python APIs, built-in exceptions such as ValueError,
TypeError etc. may also be raised).

HTTPError is the subclass of URLError raised in the specific case of
HTTP URLs.

The exception classes are exported from the urllib.error module.

URLError¶

Often, URLError is raised because there is no network connection (no route to
the specified server), or the specified server doesn’t exist. In this case, the
exception raised will have a ‘reason’ attribute, which is a tuple containing an
error code and a text error message.

e.g.

>>> req = urllib.request.Request('http://www.pretend_server.org')
>>> try: urllib.request.urlopen(req)
... except urllib.error.URLError as e:
...     print(e.reason)      
...
(4, 'getaddrinfo failed')

HTTPError¶

Every HTTP response from the server contains a numeric “status code”. Sometimes
the status code indicates that the server is unable to fulfil the request. The
default handlers will handle some of these responses for you (for example, if
the response is a “redirection” that requests the client fetch the document from
a different URL, urllib will handle that for you). For those it can’t handle,
urlopen will raise an HTTPError. Typical errors include ‘404’ (page not
found), ‘403’ (request forbidden), and ‘401’ (authentication required).

See section 10 of RFC 2616 for a reference on all the HTTP error codes.

The HTTPError instance raised will have an integer ‘code’ attribute, which
corresponds to the error sent by the server.

Error Codes¶

Because the default handlers handle redirects (codes in the 300 range), and
codes in the 100–299 range indicate success, you will usually only see error
codes in the 400–599 range.

http.server.BaseHTTPRequestHandler.responses is a useful dictionary of
response codes in that shows all the response codes used by RFC 2616. The
dictionary is reproduced here for convenience

# Table mapping response codes to messages; entries have the
# form {code: (shortmessage, longmessage)}.
responses = {
    100: ('Continue', 'Request received, please continue'),
    101: ('Switching Protocols',
          'Switching to new protocol; obey Upgrade header'),

    200: ('OK', 'Request fulfilled, document follows'),
    201: ('Created', 'Document created, URL follows'),
    202: ('Accepted',
          'Request accepted, processing continues off-line'),
    203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
    204: ('No Content', 'Request fulfilled, nothing follows'),
    205: ('Reset Content', 'Clear input form for further input.'),
    206: ('Partial Content', 'Partial content follows.'),

    300: ('Multiple Choices',
          'Object has several resources -- see URI list'),
    301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
    302: ('Found', 'Object moved temporarily -- see URI list'),
    303: ('See Other', 'Object moved -- see Method and URL list'),
    304: ('Not Modified',
          'Document has not changed since given time'),
    305: ('Use Proxy',
          'You must use proxy specified in Location to access this '
          'resource.'),
    307: ('Temporary Redirect',
          'Object moved temporarily -- see URI list'),

    400: ('Bad Request',
          'Bad request syntax or unsupported method'),
    401: ('Unauthorized',
          'No permission -- see authorization schemes'),
    402: ('Payment Required',
          'No payment -- see charging schemes'),
    403: ('Forbidden',
          'Request forbidden -- authorization will not help'),
    404: ('Not Found', 'Nothing matches the given URI'),
    405: ('Method Not Allowed',
          'Specified method is invalid for this server.'),
    406: ('Not Acceptable', 'URI not available in preferred format.'),
    407: ('Proxy Authentication Required', 'You must authenticate with '
          'this proxy before proceeding.'),
    408: ('Request Timeout', 'Request timed out; try again later.'),
    409: ('Conflict', 'Request conflict.'),
    410: ('Gone',
          'URI no longer exists and has been permanently removed.'),
    411: ('Length Required', 'Client must specify Content-Length.'),
    412: ('Precondition Failed', 'Precondition in headers is false.'),
    413: ('Request Entity Too Large', 'Entity is too large.'),
    414: ('Request-URI Too Long', 'URI is too long.'),
    415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
    416: ('Requested Range Not Satisfiable',
          'Cannot satisfy request range.'),
    417: ('Expectation Failed',
          'Expect condition could not be satisfied.'),

    500: ('Internal Server Error', 'Server got itself in trouble'),
    501: ('Not Implemented',
          'Server does not support this operation'),
    502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
    503: ('Service Unavailable',
          'The server cannot process the request due to a high load'),
    504: ('Gateway Timeout',
          'The gateway server did not receive a timely response'),
    505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
    }

When an error is raised the server responds by returning an HTTP error code
and an error page. You can use the HTTPError instance as a response on the
page returned. This means that as well as the code attribute, it also has read,
geturl, and info, methods as returned by the urllib.response module:

>>> req = urllib.request.Request('http://www.python.org/fish.html')
>>> try:
...     urllib.request.urlopen(req)
... except urllib.error.HTTPError as e:
...     print(e.code)
...     print(e.read())  
...
404
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">nnn<html
  ...
  <title>Page Not Found</title>n
  ...

Wrapping it Up¶

So if you want to be prepared for HTTPError or URLError there are two
basic approaches. I prefer the second approach.

Number 1¶

from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request(someurl)
try:
    response = urlopen(req)
except HTTPError as e:
    print('The server couldn't fulfill the request.')
    print('Error code: ', e.code)
except URLError as e:
    print('We failed to reach a server.')
    print('Reason: ', e.reason)
else:
    # everything is fine

Note

The except HTTPError must come first, otherwise except URLError
will also catch an HTTPError.

Number 2¶

from urllib.request import Request, urlopen
from urllib.error import URLError
req = Request(someurl)
try:
    response = urlopen(req)
except URLError as e:
    if hasattr(e, 'reason'):
        print('We failed to reach a server.')
        print('Reason: ', e.reason)
    elif hasattr(e, 'code'):
        print('The server couldn't fulfill the request.')
        print('Error code: ', e.code)
else:
    # everything is fine

info and geturl¶

The response returned by urlopen (or the HTTPError instance) has two
useful methods info() and geturl() and is defined in the module
urllib.response..

geturl — this returns the real URL of the page fetched. This is useful
because urlopen (or the opener object used) may have followed a
redirect. The URL of the page fetched may not be the same as the URL requested.

info — this returns a dictionary-like object that describes the page
fetched, particularly the headers sent by the server. It is currently an
http.client.HTTPMessage instance.

Typical headers include ‘Content-length’, ‘Content-type’, and so on. See the
Quick Reference to HTTP Headers
for a useful listing of HTTP headers with brief explanations of their meaning
and use.

Openers and Handlers¶

When you fetch a URL you use an opener (an instance of the perhaps
confusingly-named urllib.request.OpenerDirector). Normally we have been using
the default opener — via urlopen — but you can create custom
openers. Openers use handlers. All the “heavy lifting” is done by the
handlers. Each handler knows how to open URLs for a particular URL scheme (http,
ftp, etc.), or how to handle an aspect of URL opening, for example HTTP
redirections or HTTP cookies.

You will want to create openers if you want to fetch URLs with specific handlers
installed, for example to get an opener that handles cookies, or to get an
opener that does not handle redirections.

To create an opener, instantiate an OpenerDirector, and then call
.add_handler(some_handler_instance) repeatedly.

Alternatively, you can use build_opener, which is a convenience function for
creating opener objects with a single function call. build_opener adds
several handlers by default, but provides a quick way to add more and/or
override the default handlers.

Other sorts of handlers you might want to can handle proxies, authentication,
and other common but slightly specialised situations.

install_opener can be used to make an opener object the (global) default
opener. This means that calls to urlopen will use the opener you have
installed.

Opener objects have an open method, which can be called directly to fetch
urls in the same way as the urlopen function: there’s no need to call
install_opener, except as a convenience.

Basic Authentication¶

To illustrate creating and installing a handler we will use the
HTTPBasicAuthHandler. For a more detailed discussion of this subject –
including an explanation of how Basic Authentication works — see the Basic
Authentication Tutorial.

When authentication is required, the server sends a header (as well as the 401
error code) requesting authentication. This specifies the authentication scheme
and a ‘realm’. The header looks like: WWW-Authenticate: SCHEME
realm="REALM"
.

e.g.

WWW-Authenticate: Basic realm="cPanel Users"

The client should then retry the request with the appropriate name and password
for the realm included as a header in the request. This is ‘basic
authentication’. In order to simplify this process we can create an instance of
HTTPBasicAuthHandler and an opener to use this handler.

The HTTPBasicAuthHandler uses an object called a password manager to handle
the mapping of URLs and realms to passwords and usernames. If you know what the
realm is (from the authentication header sent by the server), then you can use a
HTTPPasswordMgr. Frequently one doesn’t care what the realm is. In that
case, it is convenient to use HTTPPasswordMgrWithDefaultRealm. This allows
you to specify a default username and password for a URL. This will be supplied
in the absence of you providing an alternative combination for a specific
realm. We indicate this by providing None as the realm argument to the
add_password method.

The top-level URL is the first URL that requires authentication. URLs “deeper”
than the URL you pass to .add_password() will also match.

# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)

Note

In the above example we only supplied our HTTPBasicAuthHandler to
build_opener. By default openers have the handlers for normal situations
ProxyHandler (if a proxy setting such as an http_proxy
environment variable is set), UnknownHandler, HTTPHandler,
HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler,
FileHandler, DataHandler, HTTPErrorProcessor.

top_level_url is in fact either a full URL (including the ‘http:’ scheme
component and the hostname and optionally the port number)
e.g. "http://example.com/" or an “authority” (i.e. the hostname,
optionally including the port number) e.g. "example.com" or "example.com:8080"
(the latter example includes a port number). The authority, if present, must
NOT contain the “userinfo” component — for example "joe:password@example.com" is
not correct.

Proxies¶

urllib will auto-detect your proxy settings and use those. This is through
the ProxyHandler, which is part of the normal handler chain when a proxy
setting is detected. Normally that’s a good thing, but there are occasions
when it may not be helpful [5]. One way to do this is to setup our own
ProxyHandler, with no proxies defined. This is done using similar steps to
setting up a Basic Authentication handler:

>>> proxy_support = urllib.request.ProxyHandler({})
>>> opener = urllib.request.build_opener(proxy_support)
>>> urllib.request.install_opener(opener)

Note

Currently urllib.request does not support fetching of https locations
through a proxy. However, this can be enabled by extending urllib.request as
shown in the recipe [6].

Note

HTTP_PROXY will be ignored if a variable REQUEST_METHOD is set; see
the documentation on getproxies().

Sockets and Layers¶

The Python support for fetching resources from the web is layered. urllib uses
the http.client library, which in turn uses the socket library.

As of Python 2.3 you can specify how long a socket should wait for a response
before timing out. This can be useful in applications which have to fetch web
pages. By default the socket module has no timeout and can hang. Currently,
the socket timeout is not exposed at the http.client or urllib.request levels.
However, you can set the default timeout globally for all sockets using

import socket
import urllib.request

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

# this call to urllib.request.urlopen now uses the default timeout
# we have set in the socket module
req = urllib.request.Request('http://www.voidspace.org.uk')
response = urllib.request.urlopen(req)


Description


Genaro Pantaleon



2013-06-12 01:26:05 UTC

Version-Release number of selected component:
youtube-dl-2013.05.14-1.fc18

Additional info:
reporter:       libreport-2.1.4
cmdline:        python /bin/youtube-dl http://vk.com/video_ext.php?oid=-34450039
dso_list:       python-libs-2.7.3-13.fc18.i686
executable:     /bin/youtube-dl
kernel:         3.9.4-200.fc18.i686
runlevel:       N 5
uid:            1000

Truncated backtrace:
urllib2.py:527:http_error_default:HTTPError: HTTP Error 501: Not Implemented

Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/bin/youtube-dl/__main__.py", line 18, in <module>
    youtube_dl.main()
  File "/bin/youtube-dl/youtube_dl/__init__.py", line 603, in main
    _real_main(argv)
  File "/bin/youtube-dl/youtube_dl/__init__.py", line 587, in _real_main
    retcode = fd.download(all_urls)
  File "/bin/youtube-dl/youtube_dl/FileDownloader.py", line 705, in download
    videos = self.extract_info(url)
  File "/bin/youtube-dl/youtube_dl/FileDownloader.py", line 461, in extract_info
    ie_result = ie.extract(url)
  File "/bin/youtube-dl/youtube_dl/InfoExtractors.py", line 96, in extract
    return self._real_extract(url)
  File "/bin/youtube-dl/youtube_dl/InfoExtractors.py", line 1277, in _real_extract
    new_url = self._test_redirect(url)
  File "/bin/youtube-dl/youtube_dl/InfoExtractors.py", line 1267, in _test_redirect
    response = opener.open(HeadRequest(url))
  File "/usr/lib/python2.7/urllib2.py", line 406, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 444, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 501: Not Implemented

Local variables in innermost frame:
fp: <addinfourl at 143124076 whose fp = <socket._fileobject object at 0x86b846c>>
code: 501
hdrs: <httplib.HTTPMessage instance at 0x887e22c>
self: <urllib2.HTTPDefaultErrorHandler instance at 0x8c589ac>
req: <youtube_dl.InfoExtractors.HeadRequest instance at 0x86a11cc>
msg: 'Not Implemented'


Comment 4


Christopher Meng



2013-06-12 04:44:13 UTC

Hi,

vk.com is not supported by youtube-dl.

Please run this command:

youtube-dl --list-extractors

to see the supported websites list.

Понравилась статья? Поделить с друзьями:
  • Urllib error urlerror
  • Usbip error vhci driver is not loaded
  • Urllib error httperror http error 503 service temporarily unavailable
  • Usbip error unable to bind device on
  • Usbip error tcp connect