gpt4 book ai didi

django - 使用 "Content-Type:application/json"在 curl 中发布会给出 HTTP/1.1 400 BAD REQUEST

转载 作者:行者123 更新时间:2023-12-02 22:25:36 25 4
gpt4 key购买 nike

当我使用以下方式发出发布请求时

curl -i -d "username=rock&password=rock" http://my_VM_IP/api/1.1/json/my_login/

它生成所需的响应,生成一个像这样的 token (删节):

HTTP/1.1 200 OK
Date: Mon, 22 Oct 2012 08:37:39 GMT
Vary: Authorization,Accept-Language,Cookie,Accept-Encoding
Content-Type: text/plain
Transfer-Encoding: chunked
OK{"success": {"my_token": "required_token"}}

但是当我尝试包含一个 header 时:

curl -i -H "Content-Type:application/json" -d "username=rock&password=rock" http://my_VM_IP/api/1.1/json/my_login/ 

它给我以下错误:

HTTP/1.1 400 BAD REQUEST
Date: Mon, 22 Oct 2012 11:12:04 GMT
Vary: Authorization,Accept-Language,Cookie,Accept-Encoding
***Content-Type: text/plain***
Content-Language: en-us
Connection: close
Transfer-Encoding: chunked
Bad Request

我不明白为什么会这样。还有为什么内容类型显示 text/plain,我也尝试查看其他一些问题,例如 Why Setting POST Content-type:"Application/Json" causes a "Bad Request" on REST WebService? .它还解决了我遇到的同样问题。按照我尝试以各种格式提供数据的答案,如

{"username":"rock", "password":"rock"} 

但没有成功。提前致谢。

最佳答案

通过使用 -H "Content-Type:application/json",您可以为您的请求设置Content-Type header 。 响应 仍会返回您的 View 告诉它返回的任何内容。

要返回 Content-Type application/json 的响应,请使用以下内容:

import json
from django.http import HttpResponse

def json_response(return_vars):
'JSON-encodes return_vars returns it in an HttpResponse with a JSON mimetype'
return HttpResponse(json.dumps(return_vars), content_type = "application/json")

#Usage: return json_response({'admin_token': admin_api_token.token})

关于django - 使用 "Content-Type:application/json"在 curl 中发布会给出 HTTP/1.1 400 BAD REQUEST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13010400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com