1
我想使用REST api從我的magento網站下載訂單。REST請求適用於POSTMAN,但不適用於RestClient
我用https爲我的網站,所以當你請求http時,它會自動轉換爲https。
我的REST請求非常簡單,只需在http請求頭中包含令牌,該請求對POSTMAN工作正常,但使用我的C#代碼時,它會一直失敗。
我的RESTClient實現庫:
public class RestClient
{
public string EndPoint { get; set; }
public HttpVerb Method { get; set; }
public string ContentType { get; set; }
public string PostData { get; set; }
public string Accept { get; set; }
public RestClient(string endpoint, HttpVerb method, string postData, string contentType)
{
EndPoint = endpoint;
Method = method;
ContentType = contentType;
PostData = postData;
}
public string MakeRequest(string parameters, Dictionary<string, string> headers,
out HttpStatusCode httpStatusCode, out bool succeed)
{
httpStatusCode = HttpStatusCode.NotFound;
succeed = false;
var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
request.Method = Method.ToString();
//request.ContentLength = 0;
request.ContentType = ContentType;
if (Accept!=null && Accept != "")
request.Accept = Accept;
foreach (var entry in headers)
{
request.Headers[entry.Key] = entry.Value;
}
if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT))
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(PostData);
}
}
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
httpStatusCode = response.StatusCode;
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
}
succeed = true;
return responseValue;
}
}
catch (WebException ex)
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
return resp;
}
return "";
}
我的代碼:
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Authorization", String.Format("Bearer {0}", credential.Token));
String url = String.Format("{0}/rest/V1/orders?"
+"searchCriteria[filter_groups][0][filters][0][field]=updated_at&"
+"searchCriteria[filter_groups][0][filters][0][value]={1}&"
+"searchCriteria[filter_groups][0][filters][0][condition_type]=from&"
+"searchCriteria[filter_groups][1][filters][0][field]=updated_at&"
+"searchCriteria[filter_groups][1][filters][0][value]={2}&"
+"searchCriteria[filter_groups][1][filters][0][condition_type]=to",
credential.WebsiteURL,
updateStart.ToString(),
updateEnd.ToString());
RestClient client = new RestClient(url, HttpVerb.GET, "", "application/json");
String respJson = null;
HttpStatusCode code = HttpStatusCode.NotFound;
bool succeed = false;
try
{
respJson = client.MakeRequest("", headers, out code, out succeed);
}
catch (Exception ex)
{
}
有誰遇到過嗎?謝謝!
嘗試發佈您的代碼考慮設置的授權明確 - 這是這是不是一個最小的,完整且可驗證的示例https://stackoverflow.com/help/mcve –
添加@ ste-fu的建議,發佈您的REST請求代碼,包括您嘗試添加的任何頭文件,因爲問題通常是auth令牌。 –
它究竟如何失敗?錯誤?時間到?例外? – Mark