简体   繁体   English

无法使用urllib2将content-type设置为application / json

[英]Not possible to set content-type to application/json using urllib2

This little baby: 这个小宝贝:

import urllib2
import simplejson as json

opener = urllib2.build_opener()
opener.addheaders.append(('Content-Type', 'application/json'))
response = opener.open('http://localhost:8000',json.dumps({'a': 'b'}))

Produces the following request (as seen with ngrep): 产生以下请求(如ngrep所示):

sudo ngrep -q -d lo '^POST .* localhost:8000'

T 127.0.0.1:51668 -> 127.0.0.1:8000 [AP]
  POST / HTTP/1.1..Accept-Encoding: identity..Content-Length: 10..Host: localhost:8000..Content-Type: application/x-www-form-urlencoded..Connection: close..User-Agent:
   Python-urllib/2.7....{"a": "b"} 

I do not want that Content-Type: application/x-www-form-urlencoded . 我不希望Content-Type: application/x-www-form-urlencoded I am explicitely saying that I want ('Content-Type', 'application/json') 我明确地说我要('Content-Type', 'application/json')

What's going on here?! 这里发生了什么?!

If you want to set custom headers you should use a Request object: 如果要设置自定义标头,则应使用Request对象:

import urllib2
import simplejson as json

opener = urllib2.build_opener()
req = urllib2.Request('http://localhost:8000', data=json.dumps({'a': 'b'}),
      headers={'Content-Type': 'application/json'})
response = opener.open(req)

I got hit by the same stuff and came up with this little gem: 我被同样的东西击中并想出了这个小宝石:

import urllib2
import simplejson as json

class ChangeTypeProcessor(BaseHandler):
    def http_request(self, req):
        req.unredirected_hdrs["Content-type"] = "application/json"
        return req

opener = urllib2.build_opener()
self.opener.add_handler(ChangeTypeProcessor())
response = opener.open('http://localhost:8000',json.dumps({'a': 'b'}))

You just add a handler for HTTP requests that replaces the header that OpenerDirector previously added. 您只需为HTTP请求添加一个处理程序,该处理程序将替换OpenerDirector先前添加的标头。

Python version: Python 2.7.15 I found that in urllib2.py:1145 : Python版本: Python 2.7.15我在urllib2.py:1145发现:

        for name, value in self.parent.addheaders:
            name = name.capitalize()
            if not request.has_header(name):
                request.add_unredirected_header(name, value)

...
    def has_header(self, header_name):
        return (header_name in self.headers or
                header_name in self.unredirected_hdrs)

Otherwise, application/x-www-form-urlencoded has been in unredirected_hdrs and it won't be overwrite 否则, application/x-www-form-urlencoded已经在unredirected_hdrs中,它不会被覆盖

You can solve like 你可以解决就好


import urllib.request
from http.cookiejar import CookieJar

import json

url = 'http://www.baidu.com'
req_dict = {'k': 'v'}

cj = CookieJar()
handler = urllib.request.HTTPCookieProcessor(cj)
opener = urllib.request.build_opener(handler)

req_json = json.dumps(req_dict)
req_post = req_json.encode('utf-8')
headers = {}
#headers['Content-Type'] = 'application/json'
req = urllib.request.Request(url=url, data=req_post, headers=headers)

#urllib.request.install_opener(opener)
#res = urllib.request.urlopen(req)
# or
res = opener.open(req)

res = res.read().decode('utf-8')

The problem is the capitalization of the Header name. 问题是标题名称的大写。 You should use Content-type and not Content-Type . 您应该使用Content-type而不是Content-Type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM