[英]Converting a cURL command into C# UWP
我有以下返回正确结果的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#代码以进行等效操作,但是运行它时出现错误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;
DefaultRequestHeaders.Accept
指定您的请求的Accept
标头。 在您的情况下,您还需要指定一个Content-Type
。
要将Content-Type
标头添加到请求中,您应该对HttpStringContent
类使用其他构造函数:
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" ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.