0

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":"[email protected]"}' 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\":\"[email protected]\",\"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;

2
  • Is the try-parse-add method actually returning true? I want to say you just need application/json for it as well, without the other content types. Commented Jan 31, 2018 at 16:38
  • I changed the TryParseAdd to only add application/json. Checked to make sure it was actually being added, which it was. This did not fix the problem. Commented Jan 31, 2018 at 21:11

1 Answer 1

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\":\"[email protected]\",\"password\":\"My-Password\",\"isPersistent\":true}", 
           UnicodeEncoding.Utf8,
           "application/json" ) );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.