我尝试使用 C# HttpWebRequest 通过 http 请求访问数据服务。当 ContentType 为 x-www-form-urlencoded 时,它可以工作。但是我需要在该请求中传输文件,所以我使用了 multipart/form-data 并遇到了来自服务的 401 错误。看起来我需要以某种方式将文件放入 x-www-form-urlencoded,但是如何?
我在 php 中有工作代码。谁能解释一下它在生成的请求中使用什么 ContenType 以及之后如何对文件进行编码?
<?php
function encode($str) {
return iconv("WINDOWS-1251", "UTF-8", $str);
}
function decode(&$resp) {
if (is_array($resp)) {
foreach ($resp as $key => $value) {
if (is_string($value))
$resp[$key] = iconv('UTF-8','WINDOWS-1251', $value);
else
decode($value);
}
}
}
$url = "https://demo.krate.ru/api/v1/reports.json";
$api_key = "zzVAhVCj6rg1dAzAXo_c";
$request = array(
'request[acceptance]' => '@d:/Users/RangerX/Downloads/YvFuRusNvwk.jpg',
'request[passport_scan]' => '@d:/Users/RangerX/Downloads/YvFuRusNvwk.jpg',
'request[reg_idx]' => '445000'
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_CAINFO, "d:\\Dev\\Projects\\krate2_demo\\doc\\v1-api-client-example\\AddTrustExternalCARoot.crt");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 && $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
// chcp 65001
var_dump($response);
?>