I have the following CURL command that returns a correct result ( ID & Password have been changed to protect the innocent ):
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:
//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;
The DefaultRequestHeaders.Accept
specifies the Accept
header for your request. In your case you need to specify a Content-Type
as well.
To add the Content-Type
header to the request, you should use a different constructor for the HttpStringContent
class :
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" ) );
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.