簡體   English   中英

將cURL命令轉換為C#UWP

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM