我想使用REST api从我的magento网站下载订单。
我在我的网站上使用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)
{
}
以前有人见过吗?谢谢!
答案 0 :(得分:0)
看起来好像你从未在任何地方设置Accept
标题。这不太可能导致Not Authorized错误,但不是你的api所以谁知道。
您也可以考虑通过在构造函数或MakeRequest
方法中传递令牌,然后使用
request.Headers.Add("Authorization", myAuthorizationToken);