0
早安全部, 我一直在尋找一個答案我的問題一段時間,但我還沒有找到任何東西。 我需要做一個REST調用到的WebAPI,這是我與捲曲使用的代碼:如何在C#Webrequest中翻譯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'
我已經能夠寫出下面的代碼在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;
}
}
但作爲迴應,我總是得到一個JSON對象,裏面說:
"{\"errors\":{\"url\":\"url or image field required\"}}"
有人請給我一些幫助嗎? 謝謝
UPDATE: 問題解決了,我只是缺少在Content-Type字段最後d。 謝謝大家!
「PostData」和「ContentType」的定義在哪裏? – Eris
@Eris它們在我創建的類中定義爲參數。我發佈的這段代碼是該類的一種方法。謝謝 – mik1904
您應該[UrlEncode](https://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode(v = vs.110).aspx)POST參數的值,像這樣:'PostData + =「url =」+ HttpUtility.UrlEncode(「http://example.com/some_image.jpg」);'如果這不起作用,請使用[Fiddler](http://www.telerik.com/fiddler)查看使用cUrl和您的代碼所做的確切請求,並找出差異。 – qbik