php - 将 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。任何帮助表示赞赏
解决方案
好的,这是解决方案:
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,这里是第一次调用来接收访问令牌。
推荐阅读
- asp.net - openapi-generator-cli:更改生成的方法名称
- javascript - 单击按钮后无法从按钮导航 - 赛普拉斯
- firebase - 如何在不使用控制台的情况下获取 Firebase 服务器密钥和发件人 ID
- clojure - 如何将可变参数函数的其余参数传递给另一个函数?
- usrp - 在 python 中使用 UHD 设置 USRP 发送器
- java - 如何将excel表复制到同一个工作簿?
- python - 使用第一列作为 colNames 旋转 pandas 数据框
- mysql - MySQL插入不存在的地方不起作用
- angular - 由于 Angular 中的服务调用延迟,数组未正确更新
- python - 如何用python解析嵌套的json