相当于Java代码的Python代码无法按预期工作

时间:2017-08-22 21:37:20

标签: java python

我正在向服务器发送请求以获取某些信息。它在Java代码中工作得非常好,但我必须将其转换为Python代码。

执行服务器请求的Java代码

HttpPost httppost = new HttpPost("https://someWebsite.com/" + this.url +
                    "?d=android&v=1.9.0&time=" + this.getCurrentTicks() +
                    "&dummy=" + this.getCurrentDummy() + "&s=" + this.hash);

// Request headers
httppost.addHeader("X-HTTP-Method-Override", "POST");
httppost.addHeader("Accept", "application/vnd.application.btb4-v1.0+json");
httppost.addHeader("Authorization", "token " + this.authToken);
httppost.addHeader("Content-Type", "application/json; charset=UTF-8");

// Request body
String json = "{\"ad_id\":\"" + this.adId + "\",\"user_id\":\"" + this.userId + "\"}";
StringEntity entityBody = new StringEntity(json);
//System.out.println(entityBody);
httppost.setEntity(entityBody);

//Execute and get the response
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

Python代码尝试一次

URL = "https://tt2.someWebsite.com/{requestPath}?d=android&v={version}&time={currentTicks}&dummy={dummy}&s={hashValue}"
URL = URL.format(requestPath  = requestPath,
                 version      = self.version,
                 currentTicks = self.get_ticks(),
                 dummy        = self.get_dummy(),
                 hashValue    = self.get_hash_value()
                 )

data = {"ad_id": self.adID,
    "user_id": self.userID}

serverRequest = urllib.request.Request(URL)
serverRequest.add_header("X-HTTP-Method-Override", "POST")
serverRequest.add_header("Accept", "application/vnd.application.btb4-v1.0+json")
serverRequest.add_header("Authorization", "token " + self.authToken)
serverRequest.add_header("Content-Type", "application/json; charset=UTF-8")
response = urllib.request.urlopen(serverRequest, data = json.dumps(data))
content  = response.read()

Python代码尝试两个

URL = "https://tt2.someWebsite.com/{requestPath}?d=android&v={version}&time={currentTicks}&dummy={dummy}&s={hashValue}"
URL = URL.format(requestPath  = requestPath,
                 version      = self.version,
                 currentTicks = self.get_ticks(),
                 dummy        = self.get_dummy(),
                 hashValue    = self.get_hash_value()
                 )

data = {"ad_id": self.adID,
     "user_id": self.userID}

headers = {"X-HTTP-Method-Override": "POST",
           "Accept": "application/vnd.application.btb4-v1.0+json",
           "Authorization": "token " + self.authToken,
           "Content-Type": "application/json; charset=UTF-8"}

r = requests.post(URL, data = json.dumps(data), headers = headers)

我不明白我错过了什么?两个python示例都收到错误400

1 个答案:

答案 0 :(得分:0)

数据kwarg到requests.post期望制作一个表单编码的帖子。尝试使用requests.post(URL, data=BytesIO(json.dumps(data)), headers=headers)。请务必from io import BytesIO