了解cURL请求(C#)

时间:2017-05-08 16:12:04

标签: c# web-services curl httprequest

我正在查看一些文档,这些文档仅显示如何在cURL中发送Web请求的示例,但是我正在使用.NET并且正在尝试了解如何发送相同的请求但使用c#

我正在尝试发送的请求的一些示例:

curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27"

带有示例参数:

{
  "text": "IBM is an American multinational technology company headquartered in Armonk, New York, United States, with operations in over 170 countries.",
  "features": {
    "entities": {
      "emotion": true,
      "sentiment": true,
      "limit": 2
    },
    "keywords": {
      "emotion": true,
      "sentiment": true,
      "limit": 2
    }
  }
}

我已经做过几次尝试在C#中点击API但没有成功,总是得到Bad Request响应所以我一定做错了。以下是我做过的一些尝试:

尝试1:

string url = $"{Properties.Settings.Default.WatsonLanguageUnderstandingUrl}/v1/analyze?version=2017-02-27";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            string auth = $"{Properties.Settings.Default.WatsonLanguageUnderstandingUsername}:{Properties.Settings.Default.WatsonLanguageUnderstandingPassword}";
            string auth64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
            string credentials = $"Basic {auth64}";

            httpWebRequest.Headers[HttpRequestHeader.Authorization] = credentials;
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = JsonConvert.SerializeObject(new
                {
                    features = new
                    {
                        entities = new
                        {
                            emotion = true,
                            sentiment = true,
                            limit = 2
                        },
                        keywords = new
                        {
                            emotion = true,
                            sentiment = true,
                            limit = 2
                        }
                    }
                });

                streamWriter.Write(json);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }

尝试2:

var authValue = new AuthenticationHeaderValue(
                "Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Properties.Settings.Default.WatsonLanguageUnderstandingUsername}:{Properties.Settings.Default.WatsonLanguageUnderstandingPassword}")));

            var client = new HttpClient() { DefaultRequestHeaders = {Authorization = authValue} };

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var anonString = new
            {
                text = "IBM is an American multinational technology company headquartered in Armonk, New York, United States, with operations in over 170 countries.",
                features = new
                {
                    entities = new
                    {
                        emotion = true,
                        sentiment = true,
                        limit = 2
                    },
                    keywords = new
                    {
                        emotion = true,
                        sentiment = true,
                        limit = 2
                    }
                }
            };
            string json = JsonConvert.SerializeObject(anonString);

            HttpResponseMessage blah = await client.PutAsync($"{ Properties.Settings.Default.WatsonLanguageUnderstandingUrl}/v1/analyze?version=2017-02-27", new StringContent(json)).ConfigureAwait(false);

尝试3:

Dictionary<string, string> parameters = new Dictionary<string, string>
            {
                { "version", "2017-02-27" },
                { "features", "sentiment" }
            };
            string queryParameters = DictToString(parameters);
            var thing = new {text = angry };
            string json = JsonConvert.SerializeObject(thing);

            string url = $"{Properties.Settings.Default.WatsonLanguageUnderstandingUrl}/v1/analyze?{queryParameters}";

            string result;
            using (WebClient client = new WebClient())
            {
                client.UseDefaultCredentials = true;
                client.Credentials = new NetworkCredential(Properties.Settings.Default.WatsonLanguageUnderstandingUsername, Properties.Settings.Default.WatsonLanguageUnderstandingPassword);
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                result = client.UploadString(url, "POST", json);
            }

我的DictToString()方法如下:

private static string DictToString(Dictionary<string, string> dict)
        {
            StringBuilder builder = new StringBuilder();

            foreach (KeyValuePair<string, string> kvp in dict)
            {
                builder.Append(kvp.Key + "=" + kvp.Value + "&");
            }

            return builder.ToString();
        }

请注意,尝试3可以运行并返回一个ok请求,但是我无法尝试使用所有这些示例参数等等。

为什么我的请求不起作用的任何帮助都会很棒!感谢

0 个答案:

没有答案