简体   繁体   English

将cURL命令转换为C#UWP

[英]Converting a cURL command into C# UWP

I have the following CURL command that returns a correct result ( ID & Password have been changed to protect the innocent ): 我有以下返回正确结果的CURL命令( 已更改ID和密码以保护无辜的人 ):

curl -H "Content-Type:application/json" -X POST -d '{"isPersistent":true,"password":"My-Password","username":"test@yahoo.com"}' https://monitor.us.sunpower.com/CustomerPortal/Auth/Auth.svc/Authenticate

I have written the following Windows UWP C# code to do the equivalent, but I get a ERROR 400 response when I run it: 我已经编写了以下Windows UWP C#代码以进行等效操作,但是运行它时出现错误400响应:

//Create an HTTP client object
Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

var headers = httpClient.DefaultRequestHeaders;
httpClient.DefaultRequestHeaders.Accept.TryParseAdd("application/json, text/plain, */*");

Uri requestUri = new Uri("https://monitor.us.sunpower.com/CustomerPortal/Auth/Auth.svc/Authenticate");

Windows.Web.Http.HttpResponseMessage httpResponse = new     Windows.Web.Http.HttpResponseMessage();
string httpResponseBody = "";

try
{
    //Send the POST request
    httpResponse = await httpClient.PostAsync(requestUri, new HttpStringContent("{\"username\":\"test@yahoo.com\",\"password\":\"My-Password\",\"isPersistent\":true}"));
    httpResponse.EnsureSuccessStatusCode();
    httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
    var x = 1;
    httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}

Any suggestions on how to get this working? 关于如何使它工作的任何建议?

Thanks! 谢谢!

var i = 1; var i = 1;

The DefaultRequestHeaders.Accept specifies the Accept header for your request. DefaultRequestHeaders.Accept指定您的请求的Accept标头。 In your case you need to specify a Content-Type as well. 在您的情况下,您还需要指定一个Content-Type

To add the Content-Type header to the request, you should use a different constructor for the HttpStringContent class : 要将Content-Type标头添加到请求中,您应该对HttpStringContent使用其他构造函数:

public HttpStringContent(String content, UnicodeEncoding encoding, String mediaType)

So the right usage would be: 因此正确的用法是:

httpResponse = await httpClient.PostAsync(
       requestUri, 
       new HttpStringContent( 
           "{\"username\":\"test@yahoo.com\",\"password\":\"My-Password\",\"isPersistent\":true}", 
           UnicodeEncoding.Utf8,
           "application/json" ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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