C# 401尝试连接到Lighthouse API时出错
我正在尝试使用C代码连接Lighthouse api。这是一个php示例,它描述了如何做到这一点。但我对它感到失望。我尝试了NetworkCredentials和send这两个标题,但仍然有401个未经授权的访问权限,下面是代码:C# 401尝试连接到Lighthouse API时出错,c#,api,lighthouse,C#,Api,Lighthouse,我正在尝试使用C代码连接Lighthouse api。这是一个php示例,它描述了如何做到这一点。但我对它感到失望。我尝试了NetworkCredentials和send这两个标题,但仍然有401个未经授权的访问权限,下面是代码: public string RequestResponse() { HttpWebRequest webRequest = WebRequest.Create(HomeUrl) as HttpWebRequest; webRequest.Method
public string RequestResponse()
{
HttpWebRequest webRequest = WebRequest.Create(HomeUrl) as HttpWebRequest;
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
string auth = CreateAuthorization("domain.lhlive.com", "user", "token");
webRequest.Headers["auth"] = "Basic " + auth;
//webRequest.Credentials = new NetworkCredential("user", "token");
//webRequest.PreAuthenticate = true;
//webRequest.Headers.Add("auth", "user, token");
webRequest.Accept = "application/vnd.lighthouse.v1.hal+json";
Stream responseStream = null;
StreamReader responseReader = null;
string responseData = "";
try
{
WebResponse webResponse = webRequest.GetResponse();
responseStream = webResponse.GetResponseStream();
responseReader = new StreamReader(responseStream);
responseData = responseReader.ReadToEnd();
}
finally
{
if (responseStream != null)
{
responseStream.Close();
responseReader.Close();
}
}
return responseData;
}
public void Test()
{
using (var client = new WebClient())
{
client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
client.Headers["ContentType"] = "application/json";
client.Headers["Accept"] = "application/vnd.lighthouse.v1.hal+json";
//client.Headers["Lighthouse Username"] = "user";
//client.Headers["API Key"] = "token";
client.Headers["WWW-Authenticate"] = "user, token";
byte[] arr = client.DownloadData("https://domain.lhlive.com/contacts");
Console.WriteLine("--- WebClient result ---");
Console.WriteLine(arr.Length);
}
}
有人知道我该怎么做吗?很难说,因为我无法访问Lighthouse,但请尝试以下操作(注意auth header是如何设置的)
在这种情况下,您的
授权
标题看起来像“基本ew91cib1c2vybmftztp5b3vyiefqsbrzxk=“
”,位于var response=webRequest.GetResponse()行上;我有以下错误附加信息:远程服务器返回错误:(405)方法不允许。对于codeWell,资源不允许使用动词。更改url或方法?至少它不再是未经授权的。我正在更改为另一个方法&它再次返回401错误…只是忘记在您的示例中添加accept方法,在这之后它的工作是正确的
var webRequest = WebRequest.Create("http://some.endpoint.com/") as HttpWebRequest;
webRequest.Method = "GET";
webRequest.Accept = "application/vnd.lighthouse.v1.hal+json";
webRequest.ContentType = "application/json";
webRequest.Headers["Authorization"] = string.Format("Basic {0}",
Convert.ToBase64String(Encoding.Default.GetBytes(
string.Format("{0}:{1}", "your username", "your API key"))));
var response = webRequest.GetResponse();
var stream = response.GetResponseStream();
var data = (new StreamReader(stream)).ReadToEnd();