cURL to C# webrequest

若如初见. 提交于 2019-12-12 15:28:21

问题


I am trying to convert a cURL script to a C# script. If I want to POST an image do I have to convert it to a string?

When I try running my script I get an exception from the target machine. Unfortunately I don't have access to see the code on the target machine.

$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);

This is what I have come up with:

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();

Any ideas?


回答1:


Possibly there is problem with the Authorization header and replacing:

string authInfo = "usr:pwd";
request.Headers["Authorization"] = "Basic " + authInfo;

with:

request.UseDefaultCredentials = false;
request.Credentials = new NetworkCredential(user, pwd);

might solve the problem.




回答2:


Before writing the buffer into the stream, make sure to convert it to a base64 string:

string result = System.Convert.ToBase64String(buffer);


来源:https://stackoverflow.com/questions/9421061/curl-to-c-sharp-webrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!