将cURL命令转换为C#UWP

时间:2018-01-31 16:28:55

标签: c# json curl uwp httpclient

我有以下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

我已经编写了以下Windows UWP C#代码来执行相同的操作,但是当我运行它时会收到ERROR 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;
}

有关如何使其正常工作的任何建议吗?

谢谢!

var i = 1;

1 个答案:

答案 0 :(得分:1)

DefaultRequestHeaders.Accept为您的请求指定Accept标头。在您的情况下,您还需要指定Content-Type

要为请求添加Content-Type标头,您应该为HttpStringContent class使用不同的构造函数:

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

所以正确的用法是:

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