Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cURL to C# webrequest

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?

like image 832
Jan Lund Madsen Avatar asked Dec 19 '25 18:12

Jan Lund Madsen


1 Answers

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.

like image 57
jahu Avatar answered Dec 22 '25 08:12

jahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!