【问题标题】:Converting a cURL command into C# UWP将 cURL 命令转换为 C# UWP
【发布时间】:2018-01-31 16:28:55
【问题描述】:

我有以下返回正确结果的 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;
}

关于如何使它工作的任何建议?

谢谢!

变量 i = 1;

【问题讨论】:

  • try-parse-add 方法真的返回 true 吗?我想说你也只需要application/json,不需要其他内容类型。
  • 我将 TryParseAdd 更改为仅添加应用程序/json。检查以确保它实际上是被添加的,它确实是。这并没有解决问题。

标签: c# json curl uwp httpclient


【解决方案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" ) );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2019-03-25
    • 2017-01-01
    • 1970-01-01
    相关资源
    最近更新 更多