我一直在尝试将以下PHP curl查询转换为Python请求时遇到一些问题。
$cfile = new CURLFile($filePath,$fileType,$filename);
$request='{"signers":["abc@xyz.com"],"expire_in_days":10, "display_on_page":"all"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('authorization: Basic Base64encode(client_id:client_secret)'));
$post = array('file'=>$cfile,'request' =>$request);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$res = curl_exec($ch)
request_data = {}
request_data['signers'] = ['abc@xyz.com']
request_data['expire_in_days'] = 10
request_data['display_on_page'] = 'all'
temp_file_path = 'PdfTest.pdf'
files = {'file': open(temp_file_path, 'rb')}
headers = {}
headers['content-type'] = "multipart/form-data"
headers['authorization'] = 'Basic '+auth # auth contains b64 client:secret
r = requests.post(url, files=files, data={'request': request_data}, headers=headers)
考虑我的请求网址是相同的,授权的基础64值也是如此。 PHP代码从服务器返回正确的响应,但Python奇怪地说,提供了一个响应告诉"code":"UNSUPPORTED_MEDIA_TYPE"
答案 0 :(得分:1)
经过一些检查后,我似乎发现问题出在以下几行,files
需要强制filetype
,可以从MimeTypes().guess_type(path)[0]
和request_data
获取应该是json.dumps(request_data)
files = {'file': (temp_file_path, open(temp_file_path, 'rb'), filetype)}
# .... Other code
r = requests.post(url, files=files, data={'request': json.dumps(request_data)}, headers=headers)
答案 1 :(得分:0)
$url_0 = 'https://pranatrader.ir/services/LoginUser';
$post_filed = 'username=0061625671&password=db00d9250ef8a9243e6d9bc1e960f09d1aaf517a&preferredClientID=Mobile&ip=undefined';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url_0");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_filed);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'cache-control: no-cache',
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: 107',
'Host: pranatrader.ir',
'Connection: Keep-Alive',
'User-Agent: okhttp/3.12.1'
));
$server_output = curl_exec($ch);
#echo '<xmp>' . print_r($server_output, true) . '</xmp>';
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($server_output, 0, $header_size);
$body = substr($server_output, $header_size);
$json_result = json_decode($body);
echo '<xmp>' . print_r($json_result, true) . '</xmp>';
curl_close($ch);