C# 非常简单的WebRequest调用web服务每次调用两个调用,一个没有凭据,另一个有?
我用一个密钥/密码调用Shopify的API,这个非常基本的方法调用每次调用两次。我使用“Charles Proxy”来监听呼叫,它所做的一切都是双重的,一个带有auth,一个没有 请看屏幕截图。我做错了什么C# 非常简单的WebRequest调用web服务每次调用两个调用,一个没有凭据,另一个有?,c#,.net,web-services,json.net,httpwebrequest,C#,.net,Web Services,Json.net,Httpwebrequest,我用一个密钥/密码调用Shopify的API,这个非常基本的方法调用每次调用两次。我使用“Charles Proxy”来监听呼叫,它所做的一切都是双重的,一个带有auth,一个没有 请看屏幕截图。我做错了什么 public string GetJsonReply(string _requestURL) { string json; WebRequest req = WebRequest.Create(_requestURL); r
public string GetJsonReply(string _requestURL)
{
string json;
WebRequest req = WebRequest.Create(_requestURL);
req.Method = WebRequestMethods.Http.Get;
req.Credentials = new NetworkCredential(APIKey, Password);
try
{
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
json = sr.ReadToEnd();
}
}
}
catch (Exception e)
{
json = e.GetBaseException().ToString();
}
return json;
}
编辑:调用该方法的方式如下:
public IdBillingContract GetBillingAddressInfo(string _id)
{
string url = "https://myurl.myshopify.com/admin/orders/" + Uri.EscapeDataString(_id) + ".json?fields=id,billing_address";
return JsonConvert.DeserializeObject<IdBillingContract>(GetJsonReply(url), _serializerSettings);
}
public IdBillingContract GetBillingAddressInfo(字符串\u id)
{
字符串url=”https://myurl.myshopify.com/admin/orders/“+Uri.EscapeDataString(_id)+”.json?字段=id,账单地址”;
返回JsonConvert.DeserializeObject(GetJsonReply(url),\u serializerSettings);
}
问题在于您使用的是凭证
属性。不要使用它,因为.NET正在后台循环尝试不同的身份验证协议,如NTLM等
public string GetJsonReply(string _requestURL)
{
string json = string.Empty;
string apiKey = "Foo";
string password = "Bar";
string credentialsFormatted = string.Format("{0}:{1}",apiKey,password);
byte[] credentialBytes = Encoding.ASCII.GetBytes(credentialsFormatted);
string basicCredentials = Convert.ToBase64String(credentialBytes);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_requestURL);
request.Method = WebRequestMethods.Http.Get;
request.Headers["Authorization"] = "Basic " + basicCredentials;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
json = reader.ReadToEnd();
}
}
catch (Exception e)
{
json = e.GetBaseException().ToString();
}
return json;
}
对这个方法的调用在哪里?它是如何调用的。。?如果这是一个网页,可能会出现一些“回发问题”,这意味着它会调用页面加载两次。。你能说明它是如何被调用的吗?哪个请求首先发生:有auth的还是没有auth的?您的
json
字符串中包含哪些数据?没有auth的数据首先出现。我用调用它的方法编辑了这个问题,它在同一个类中。