错误" 400错误请求"使用Python将JSON对象发送到api时

时间:2017-03-24 18:08:26

标签: python json python-requests

以下是一段代码:

public void method() {
    vehicles = new ArrayList<>();

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            vehicles.add(new Vehicle());
        }
    });
    // Here you start the Thread 
    t.start();
    // But there is no guaranty that on this line the "run" function of the Thread has been called
    // And if it has not been called then vehicules is empty
    AlertDialog.Builder b = new AlertDialog.Builder(CONTEXT);
    b.setMessage(vehicles.size());
    b.create().show();
    // b displays 0 here
}

以下是我的尝试:

api_url = {url}
auth_head = {key: value} << my api authentication header
data = {'title':'Python'}  << the valid json object format that the api accepts

这是输出:
&#34; 400错误请求&#34;

为了确保url和我的api令牌密钥正常工作,我尝试了GET:

data = json.dumps(data)
json_obj = json.loads(data)
response = requests.post(api_url, headers = auth_head, data = json_obj)
print(response.text)

输出: &#34; 200&#34;

所以url和api令牌工作正常。我觉得我没有发送api想要的正确的json对象构造

1 个答案:

答案 0 :(得分:0)

您无需以json的形式发送数据。只需将数据作为字典发送。它会接受。 requests会自动将您的字典编码为json