首页 > 解决方案 > 将 curl_setopt 转换为 asp.net 标头

问题描述

我必须从 asp.net 控制台应用程序中解决一个 Rest API。第一个调用是登录以接收访问令牌。不幸的是,所有的例子都只在我读得很差的 PHP 中。

PHP 示例说:

use 'curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Authorization : Basic ".$encodedAuth));

Token Header: "Authorization: Basic {User,Colon,Password -> as Base64}"

内容类型是application/json.

编辑:用户/密码组合使用指令设置:

curl_setopt($this->curl, CURLOPT_USERPWD, $api_username . ':' . $api_password);

我必须在我的 httpwebrequest 中设置什么才能正确传输授权?

我努力了

  Dim data As String = """grant_type"": ""client_credentials"""
  Dim postdata As Byte() = Encoding.UTF8.GetBytes(data)

  Dim req As HttpWebRequest = DirectCast(HttpWebRequest.Create(uploadURL), HttpWebRequest)
  req.Method = "POST"
  req.ContentType = "application/json;encoding=utf-8"
  req.ContentLength = postdata.Length
  req.Accept = "application/json"
  req.Credentials = New NetworkCredential(userID, userPW)
  req.Timeout = 600000
  req.Headers.Add("Authorization", userID & ":" & userPW)

但继续收到代码 400。任何帮助表示赞赏

标签: phpasp.netposthttpwebrequest

解决方案


好的,这是解决方案:

     Dim data As String = "{""grant_type"": ""client_credentials""}"
     Dim postdata As Byte() = Encoding.UTF8.GetBytes(data)

     Dim uploadURL As String = "https://api.dreamrobot.de/rest/v1.0/token.php"
     Dim userID As String = "xxxxxxx"
     Dim userPW As String = "xxxxxxx"

     Dim req As HttpWebRequest = DirectCast(HttpWebRequest.Create(loginURL), HttpWebRequest)
     req.Method = "POST"
     req.ContentType = "application/json;encoding=utf-8"
     req.ContentLength = postdata.Length
     req.Accept = "application/json"
     req.Timeout = 600000
     req.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(Encoding.UTF8.GetBytes(userID & ":" & userPW), Base64FormattingOptions.None))

     Dim _stream As Stream = req.GetRequestStream()
     _stream.Write(postdata, 0, postdata.Length)
     _stream.Close()

     Dim _response As HttpWebResponse = req.GetResponse()
     Dim _reader As New StreamReader(_response.GetResponseStream)
     data = _reader.ReadToEnd
     _reader.Close()
     _response.Close()

PHP setopt CURLOPT_USERPWD 函数创建一个 http Header 条目“Authorization:”,它需要值“Basic”和 base64(user:pwd)。重要的一点是在没有换行的情况下转换为base64string,因此Base64FormattingOptions.None。

这里的用例是处理 DreamRobot Rest API,这里是第一次调用来接收访问令牌。


推荐阅读