简体   繁体   English

如何在C#Webrequest中翻译cURL?

[英]How to translate cURL in a C# Webrequest?

Good morning all, I have been looking for an answer to my question for a while but I haven't found anything. 早上好,我一直在寻找问题的答案,但是我什么都没找到。 I need to make a REST call to a Webapi, this is the code that I use with cURL: 我需要对Webapi进行REST调用,这是与cURL一起使用的代码:

curl -X POST --include 'https://animetrics.p.mashape.com/detect?api_key=sample' \
  -H 'X-Mashape-Key: sample' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'Accept: application/json' \
  -d 'selector=FACE, EYES, FULL' \
  -d 'url=http://example.com/some_image.jpg'

I have been able to write the following piece of code in C#: 我已经能够用C#编写以下代码:

public string MakeRequest(string parameters)
    {
        var request = (HttpWebRequest)WebRequest.Create(EndPoint);

        request.Method = Method.ToString();
        request.ContentLength = 0;
        request.ContentType = ContentType;
        request.Headers["X-Mashape-Key"] = "sample";
        request.Accept = "application/json";

        PostData += "selector=FACE&";
        PostData += "url=" +HttpUtility.UrlEncode("http://www.sample.it/sample.jpg");
        if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
        {
            var bytes= Encoding.ASCII.GetBytes(PostData);
            request.ContentLength = bytes.Length;

            using (var writeStream = request.GetRequestStream())
            {
                writeStream.Write(bytes, 0, bytes.Length);
            }
        }

        using (var response = (HttpWebResponse)request.GetResponse())
        {
            var responseValue = string.Empty;

            if (response.StatusCode != HttpStatusCode.OK)
            {
                var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                throw new ApplicationException(message);
            }

            // grab the response
            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                    using (var reader = new StreamReader(responseStream))
                    {
                        responseValue = reader.ReadToEnd();
                    }
            }

            return responseValue;
        }
    }

But as a response I always get a json object that inside says: 但是作为回应,我总是得到一个内部表示的json对象:

"{\"errors\":{\"url\":\"url or image field required\"}}"

Could someone please give me some help? 有人可以给我些帮助吗? Thank you 谢谢

UPDATE: Problem solved I was just missing a final d in the Content-Type field. 更新:问题解决了,我只是在Content-Type字段中缺少final d。 Thank you to all! 谢谢你们!

UPDATE: Problem solved I was just missing a final d in the Content-Type field and the error was not signaled from the debugger. 更新:问题解决了,我只是在Content-Type字段中缺少final d,并且调试器未发出错误消息。 Thank you to all! 谢谢你们! Michele 米歇尔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM