用C#连接认证REST服务获取JSON数据

0 投票
1 回答
674 浏览
提问于 2025-04-17 00:13

我正在尝试调用一个REST API来获取一些JSON数据,但我无法连接上。我觉得可能需要一个缓存的cookie或者其他什么东西才能正常工作。有没有人有过使用REST Bitbucket.org API的经验?我使用的API地址是 https://api.bitbucket.org/1.0/user/repositories/。如果直接在网页浏览器中使用这个地址是可以正常工作的。

        HttpWebRequest request = WebRequest.Create(
            ConfigurationManager.AppSettings["RESTApiPath"]) as HttpWebRequest;

        request.Credentials = new NetworkCredential(
            ConfigurationManager.AppSettings["user"],
            ConfigurationManager.AppSettings["pass"]);

        //request.PreAuthenticate = true;
        // Get response
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            // Get the response stream
            StreamReader reader = new StreamReader(response.GetResponseStream());
            // Console application output
            string jsonData = reader.ReadToEnd();

            if (!string.IsNullOrWhiteSpace(jsonData))
                ParseNames(jsonData);
        }

1 个回答

1

可以使用 FiddlerWireshark 来对比一下,当浏览器正常工作时和你的代码不正常时,网络上传输的数据有什么不同……一旦你了解了这些差异,就可以相应地修改你的代码……

撰写回答