将curl_setopt转换为asp.net头文件

时间:2018-05-04 13:45:44

标签: php asp.net post httpwebrequest

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

PHP示例说:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ArticleController extends Controller
{
    public function controlAction()
    {
        // ...
        dump($this->container->getParameter('smugmug.oauth_token'));
        // Or this solution
        dump($this->getParameter('smugmug.oauth_token'));
        // ...
        // return a response
    }
}

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

内容类型为Token Header: "Authorization: Basic {User,Colon,Password -> as Base64}"

编辑: user / pwd组合使用以下指令设置:

application/json.

我需要在httpwebrequest中设置什么才能正确传输授权?

我试过了

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

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

1 个答案:

答案 0 :(得分:0)

好的,这是解决方案:

     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条目"授权:"需要价值"基本" &安培; BASE64(用户:PWD)。 重要的一点是在没有换行的情况下转换为base64string,因此Base64FormattingOptions.None。

这里的用例是解决DreamRobot Rest API,这是第一次接收Access令牌的调用。