将POST请求从Java转换为Python - 无法POST数据

时间:2016-03-17 07:19:42

标签: java python http-post

我遇到的情况是需要将一个看似简单的Java代码翻译成Python。

Java代码只是向具有三个参数的URL发出POST请求。代码如下:

{
 java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
 String content = "phonenr=" + smsPhone + "&smstxt=" + smsMessage + "&Submit=SendSms";

 java.net.URL url = new java.net.URL(smsGatewayPath);
 java.net.HttpURLConnection urlCon = (java.net.HttpURLConnection) url.openConnection();

 urlCon.setReadTimeout(5000);
 urlCon.setDoInput(true);
 urlCon.setDoOutput(true);
 urlCon.setUseCaches(false);
 urlCon.setRequestMethod("POST");

 urlCon.setRequestProperty("Content-Length", Integer.toString(content.length()));
 urlCon.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
 urlCon.setRequestProperty("Authorization", "Basic " + authStringEncoded);

 java.io.DataOutputStream output = new java.io.DataOutputStream(urlCon.getOutputStream());

 output.writeBytes(content);

 output.flush();
 output.close();

 java.io.DataInputStream input = new java.io.DataInputStream(urlCon.getInputStream());

 int bufSize = 4096;
 byte[] bytesRead = new byte[bufSize];
 int bytesReadLength = 0;

 while ((bytesReadLength = input.read(bytesRead)) > 0) {
  baos.write(bytesRead, 0, bytesReadLength);
 }

 input.close();
 baos.close();

 return org.apache.commons.lang.StringEscapeUtils.unescapeJava(baos.toString("UTF-8"));

}

现在,我尝试在Python中发出相同的请求,将完全相同的数据发布到同一个URL:

import requests

SMS_BOX_URL = 'http://ip/name.cgi'

USER = "admin"
PASS = "password"

auth_string_encoded = "YWRtaW46cGFzc3dvcmQ="

headers = {"Content-Type": "text/xml;charset=UTF-8", "Authorization": "Basic %s" % auth_string_encoded}

content = {'phonenr': 'xxxxxxxxxx', 'smstext': 'Test', 'Submit': 'SendSms'}
req_post = requests.post(SMS_BOX_URL, data=content, auth=(USER,PASS), headers=headers)

print(req_post.text)
print(req_post.url)
print(req_post.status_code)

现在,我从中获得的输出是:

<html>
<head>
<title>TopexGateway</title></head>
<body bgcolor="#00CCFF" text="#000000">
ERROR
</body>
</html>

http://ip/name.cgi
200

现在我有点困惑,为什么这不起作用,因为当我提出一个CURL请求时,一切似乎都有效:

curl -v --data "phonenr=xxxxx&smstxt=Test&Submit=SendSms" http://admin:password@ip/name.cgi

Here是我收到的CURL和here我用Python收到的内容。

谁能告诉我我的python版本有什么问题?

1 个答案:

答案 0 :(得分:1)

Java:   "smstxt"
Python: "smstext"

那封信e:对人类来说是不可见的,与计算机有所不同。