dongyao1895 2016-10-19 14:09
浏览 577

如何将以下CURL调用转换为C#

I'm trying to use a bible API in an application. Here is the following Curl Call which I have to make

curl -L -u #{API Token}:X -k https://bibles.org/v2/verses/eng-GNTD:Acts.8.34.xml
  • -L option tells cURL to follow redirects.
  • -u option to specify a username and password with HTTP Basic authentication. API token is given as the username. The password is ignored by the server, so you can put whatever you want; In our case "X".
  • -k option is used to tell cURL to not verify the SSL certificate.

Now the documentation gives us a PHP code for using this API which is as below

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

I have tried changing this in C# to the following. However, I get a 401(Unauthorized code). What am i doing wrong?

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();
  • 写回答

1条回答 默认 最新

  • dongya1875 2016-10-19 14:31
    关注

    I think you are missing the Basic portion of the authentication header. This is how I would do it in .NET 4.6

    var client = new HttpClient()
    var auth = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{accountSid}:{token}"));
    
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);
    

    in your example try this:

     myReq.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(apiToken + ":X"));
    
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源