我正在尝试将cURL脚本转换为C#脚本。 如果我想POST图像,我是否必须将其转换为字符串?
当我尝试运行我的脚本时,我从目标机器获得异常。不幸的是,我无权查看目标计算机上的代码。
$ch = curl_init();
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Expect:"));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($ch, CURLOPT_USERPWD, "user:pwd");
curl_setopt($ch, CURLOPT_URL, 'http://192.168.1.105/upload.php');
$data = array('type' => 'upload', 'student' => 'Peter', 'class' => '101', 'fotograf' => 'Jane', 'file' => '@/pictures/image1.jpg');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
这就是我的想法:
WebRequest request = WebRequest.Create("http://192.168.1.105/upload.php");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
string authInfo = "usr:pwd";
request.Headers["Authorization"] = "Basic " + authInfo;
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("type=upload&student=Peter&calss=101&fotograf=Jane&file=/pictures/image1.jpg");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
WebResponse response = request.GetResponse();
有什么想法吗?
答案 0 :(得分:3)
可能是Authorization标题出现问题并替换:
string authInfo = "usr:pwd";
request.Headers["Authorization"] = "Basic " + authInfo;
使用:
request.UseDefaultCredentials = false;
request.Credentials = new NetworkCredential(user, pwd);
可能会解决问题。
答案 1 :(得分:0)
在将缓冲区写入流之前,请确保将其转换为base64字符串:
string result = System.Convert.ToBase64String(buffer);