简体   繁体   中英

What is the C# equivalent of this cURL PUT Request?

I'm trying to do the equivalent of the following in C# ...

curl --request PUT \
  --user-agent "Your Client Name/1.0" \
  --header "Authorization: Basic YWRtaW46WW91ckFQSUtleUhlcmU=" \
  --header "Content-Type: application/xml" \
  --data-binary '<order><status_id>10</status_id></order>' \
  https://www.example.com/api/v2/orders/101

My effort is giving my a 404 - Bad Request response. I've never looked at curl before. Anyone out there have any ideas?

var url = String.Format("https://www.website.com/api/v2/orders/{0}", 1647);
var credentials = Convert.ToBase64String(
               Encoding.ASCII.GetBytes(String.Format("{0}:{1}", "admin", "mypassword")));
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "PUT";
request.Headers.Add(String.Format("Authorization: Basic {0}", credentials));

var status = "<?xml version='\"1.0'\" encoding='\"UTF-8'\"?><order><status_id>2<order><status_Id>";

using (var stream = request.GetRequestStream())
{
   using (var writer = new BinaryWriter(stream))
   {
      writer.Write(status);
   }
 }

var response = request.GetResponse();

Usually 'Bad request' is because the header is malformed:

look at

 <?xml version='\"1.0'\" encoding='\"UTF-8'\"?>

it should be written as follow

<?xml version=\"1.0\" encoding=\"UTF-8\"?>

with no ' or if you want to avoid escapes you could write

<?xml version='1.0' encoding='UTF-8'?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM