尝试连接到Lighthouse API时出现401错误

时间:2014-11-24 09:57:00

标签: c# api lighthouse

我正在尝试使用C#代码连接到Lighthouse api。这是php示例https://support.lighthouserocks.com/hc/en-gb/articles/201319732-API-The-Basics,它描述了如何执行此操作。但我失败了。我试过NetworkCredentials&发送Header但仍有401 Unauthorized访问它,这是代码:

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);
    }
}

有人知道我应该做什么吗?

1 个答案:

答案 0 :(得分:2)

很难说,因为我无法访问Lighthouse,但请尝试以下方法(注意如何设置auth标头)。

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();

在这种情况下,您的Authorization标题看起来像"Basic eW91ciB1c2VybmFtZTp5b3VyIEFQSSBrZXk="