urllib.request.add_header

Here are the examples of the python api urllib.request.add_header taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1 Examples 7

Example 1

Project: sublime-browser-integration Source File: remote_connection.py
Function: request
    def _request(self, url, data=None, method=None):
        """
        Send an HTTP request to the remote server.

        :Args:
         - method - A string for the HTTP method to send the request with.
         - url - The URL to send the request to.
         - body - The message body to send.

        :Returns:
          A dictionary with the server's parsed JSON response.
        """
        LOGGER.debug('%s %s %s' % (method, url, data))

        parsed_url = parse.urlparse(url)

        if self.keep_alive:
            headers = {"Connection": 'keep-alive', method: parsed_url.path,
                       "User-Agent": "Python http auth",
                       "Content-type": "application/json;charset=\"UTF-8\"",
                       "Accept": "application/json"}
            if parsed_url.username:
                auth = base64.standard_b64encode('%s:%s' %
                       (parsed_url.username, parsed_url.password)).replace('\n', '')
                headers["Authorization"] = "Basic %s" % auth
            self._conn.request(method, parsed_url.path, data, headers)
            resp = self._conn.getresponse()
            statuscode = resp.status
        else:
            password_manager = None
            if parsed_url.username:
                netloc = parsed_url.hostname
                if parsed_url.port:
                    netloc += ":%s" % parsed_url.port
                cleaned_url = parse.urlunparse((parsed_url.scheme,
                                                   netloc,
                                                   parsed_url.path,
                                                   parsed_url.params,
                                                   parsed_url.query,
                                                   parsed_url.fragment))
                password_manager = url_request.HTTPPasswordMgrWithDefaultRealm()
                password_manager.add_password(None,
                                              "%s://%s" % (parsed_url.scheme, netloc),
                                              parsed_url.username,
                                              parsed_url.password)
                request = Request(cleaned_url, data=data.encode('utf-8'), method=method)
            else:
                request = Request(url, data=data.encode('utf-8'), method=method)

            request.add_header('Accept', 'application/json')
            request.add_header('Content-Type', 'application/json;charset=UTF-8')

            if password_manager:
                opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
                                                  HttpErrorHandler(),
                                                  url_request.HTTPBasicAuthHandler(password_manager))
            else:
                opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
                                                  HttpErrorHandler())
            resp = opener.open(request)
            statuscode = resp.code
            if not hasattr(resp, 'getheader'):
                if hasattr(resp.headers, 'getheader'):
                    resp.getheader = lambda x: resp.headers.getheader(x)
                elif hasattr(resp.headers, 'get'):
                    resp.getheader = lambda x: resp.headers.get(x)

        data = resp.read()
        try:
            if 399 < statuscode < 500:
                return {'status': statuscode, 'value': data}
            if 300 <= statuscode < 304:
                return self._request(resp.getheader('location'), method='GET')
            body = data.decode('utf-8').replace('\x00', '').strip()
            content_type = []
            if resp.getheader('Content-Type') is not None:
                content_type = resp.getheader('Content-Type').split(';')
            if not any([x.startswith('image/png') for x in content_type]):
                try:
                    data = utils.load_json(body.strip())
                except ValueError:
                    if 199 < statuscode < 300:
                        status = ErrorCode.SUCCESS
                    else:
                        status = ErrorCode.UNKNOWN_ERROR
                    return {'status': status, 'value': body.strip()}

                assert type(data) is dict, (
                    'Invalid server response body: %s' % body)
                assert 'status' in data, (
                    'Invalid server response; no status: %s' % body)
                # Some of the drivers incorrectly return a response
                # with no 'value' field when they should return null.
                if 'value' not in data:
                    data['value'] = None
                return data
            else:
                data = {'status': 0, 'value': body.strip()}
                return data
        finally:
            LOGGER.debug("Finished Request")
            resp.close()