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