簡體   English   中英

TypeError:無法將字節連接到str時如何轉換為字節

[英]How to convert to bytes when TypeError: can't concat bytes to str

我正在嘗試通過API發送數據,但遇到TypeError:無法將字節連接到str。 據我了解,這意味着我需要將部分代碼轉換為字節,但不確定如何執行此操作。 我嘗試在前面添加b或使用bytes('data'),但可能將它們放置在錯誤的區域。

import http.client

conn = http.client.HTTPSConnection("exampleurl.com")

payload = {
    'FilterId': "63G8Tg4LWfWjW84Qy0usld5i0f",
    'name': "Test",
    'description': "Test1",
    'deadline': "2017-12-31",
    'exclusionRuleName': "Exclude",
    'disable': "true",
    'type': "Type1"
    }

headers = {
    'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
    'x-csrf-token': "wWjeFkMcbopci1TK2cibZ2hczI",
    'cache-control': "no-cache",
    'postman-token': "23c09c76-3b030-eea1-e16ffd48e9"
    }


conn.request("POST", "/api/campaign/create", payload, headers)


res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

這是問題所在:

conn.request("POST", "/api/campaign/create", payload, headers)

我不確定什么以及如何轉換為字節。

如果可以的話,請使用requests ,這樣操作起來會容易得多。

否則,您需要對要發布到服務器的有效負載進行urlencode 有效負載的url編碼版本如下所示:

description=Test1&exclusionRuleName=Exclude&FilterId=63G8Tg4LWfWjW84Qy0usld5i0f&deadline=2017-12-31&type=Type1&name=Test&disable=true

這是一個工作示例:

import http.client
from urllib.parse import urlencode

conn = http.client.HTTPSConnection("httpbin.org")

payload = {
    'FilterId': "63G8Tg4LWfWjW84Qy0usld5i0f",
    'name': "Test",
    'description': "Test1",
    'deadline': "2017-12-31",
    'exclusionRuleName': "Exclude",
    'disable': "true",
    'type': "Type1"
    }

headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'x-csrf-token': "wWjeFkMcbopci1TK2cibZ2hczI",
    'cache-control': "no-cache",
    'postman-token': "23c09c76-3b030-eea1-e16ffd48e9"
    }

conn.request("POST", "/post", urlencode(payload), headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

http://httpbin.org返回此JSON響應:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "FilterId": "63G8Tg4LWfWjW84Qy0usld5i0f", 
    "deadline": "2017-12-31", 
    "description": "Test1", 
    "disable": "true", 
    "exclusionRuleName": "Exclude", 
    "name": "Test", 
    "type": "Type1"
  }, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Cache-Control": "no-cache", 
    "Connection": "close", 
    "Content-Length": "133", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "Postman-Token": "23c09c76-3b030-eea1-e16ffd48e9", 
    "X-Csrf-Token": "wWjeFkMcbopci1TK2cibZ2hczI"
  }, 
  "json": null, 
  "origin": "220.233.14.203", 
  "url": "https://httpbin.org/post"
}

請注意,我使用httpbin.org作為測試服務器,並發布到https://httpbin.org/post

另外,我將Content-type標頭更改為application / x-www-form-urlencoded,因為這是urlencode()返回的格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM