【问题标题】:POST request with python 400 Bad Request使用 python 400 错误请求的 POST 请求
【发布时间】:2017-03-03 18:11:27
【问题描述】:

在在线服务中,javascript 使用新的表单数据来获取图像,然后通过一个简单的 api 调用使用此代码检索对象。

function sendSearchImage(form) {
console.log(">>> sendSearchImage");
var image = new FormData();
image.append('refImage', readFile);

$.ajax({
        type: 'post',
        url: instore_home + '/products/query',
        contentType: false,
        processData: false,
        data: image,
        success: function (response) {
            console.log("<<< " + JSON.stringify(response));
            showQueryResults(response);
            //alert("Ref image successfully added: code " + response.refImgId);
            //alert(JSON.stringify(response));
            //window.location.reload();
        }
    });

return false;
}

我想改为在 python 中调用相同的 API,但我不断收到 400:Bad Request response,这是我到目前为止的代码

 files = {'refImage': ('1.jpg', open(os.getcwd()+"/images/1.jpg", "rb"), 'image/jpeg')}
    headers = {"Content-Type":"multipart/form-data", "User-Agent" : "Mozilla/5.0"}
    r = requests.post('Url', headers=headers, data=files)

谁能告诉我应该以哪种格式传递数据以获得良好的响应?

【问题讨论】:

    标签: javascript python api post request


    【解决方案1】:

    它可能是您用来访问网页的用户代理。在您的 headers 变量中使用此标头:

    headers = {"Content-Type":"multipart/form-data","User-Agent" : "Mozilla/5.0"}
    

    【讨论】:

    • 我尝试按照建议进行操作,但没有任何改变,我将帖子格式稍微更改为与 http 正文请求尽可能相似,但实际上我没有相关文档跨度>
    【解决方案2】:

    我通过不指定标题解决了我的疑问,它似乎是自动构建的,并且通过手动实现,您可能无法正确获取所有值,因为其中一些甚至是动态的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      相关资源
      最近更新 更多