我试图在应用程序中使用圣经API。以下是我必须做的以下卷曲调用
curl -L -u #{API Token}:X -k https://bibles.org/v2/verses/eng-GNTD:Acts.8.34.xml
现在,文档为我们提供了使用此API的PHP代码,如下所示
<?php
$token = '#{API Token}';
$url = 'https://bibles.org/v2/verses/eng-GNTD:Acts.8.34.xml';
// Set up cURL
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, $url);
// don't verify SSL certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Return the contents of the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Set up authentication
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$token:X");
// Do the request
$response = curl_exec($ch);
curl_close($ch);
print($response);
?>
我尝试在C#中将其更改为以下内容。但是,我得到了401(未经授权的代码)。我做错了什么?
string apiToken = "#{myAPIToken}";
string url = "https://bibles.org/v2/verses/eng-GNTD:Acts.8.34.xml";
WebRequest myReq = WebRequest.Create(url);
CredentialCache mycache = new CredentialCache();
myReq.Headers["Authorization"] = Convert.ToBase64String(Encoding.ASCII.GetBytes(apiToken + ":X"));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
答案 0 :(得分:0)
我认为您错过了身份验证标头的Basic
部分。这就是我在.NET 4.6中的做法
var client = new HttpClient()
var auth = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{accountSid}:{token}"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);
你的例子中的试试这个:
myReq.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(apiToken + ":X"));