0

我需要连接到一个 URL 并从中下载数据。api 文档声明必须通过 CURL 进行 POST,但我使用的是 .NET 客户端。

我想知道 .NET 中的 CURL 等价物是什么。

尝试了以下但无法让它工作

 if (Request.QueryString["code"] != null) {
       //     Response.Write(Request.QueryString["code"].ToString());

            string url = "https://company.com/token/";
            string data = "{client_id=id,client_secret=id,grant_type=authorization_code,code" + "="  + Request.QueryString["code"].ToString() + ",redirect_uri" + "=" + "http://localhost:10188/home.aspx" + ",scope=ancestry" + "}";

            WebRequest myReq = WebRequest.Create(url);
            myReq.Method = "POST";
            myReq.ContentLength = data.Length;
            myReq.ContentType = "application/json; charset=UTF-8";

            UTF8Encoding enc = new UTF8Encoding();

            using (Stream ds = myReq.GetRequestStream())
            {
                ds.Write(enc.GetBytes(data), 0, data.Length);
            }

            WebResponse response = null;
            string ret = null;

            try
            {
                response = myReq.GetResponse();
            }
            catch (WebException ex)
            {
                if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.BadRequest)
                {
                    Debug.WriteLine("Error 400 detected!!");
                }
                response = (WebResponse)ex.Response;
            }
            finally
            {
                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    ret = streamReader.ReadToEnd();
                }
            }
            Response.Write(ret);
        }

以下代码现在正在运行

using (WebClient wc = new WebClient()) {
            System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
            reqparm.Add("client_id", mycon.client_id);
            reqparm.Add("client_secret", mycon.client_secret);
            reqparm.Add("grant_type", mycon.grant_type);
            reqparm.Add("code", mycon.code);
            reqparm.Add("redirect_uri", mycon.redirect_uri);
            reqparm.Add("scope", mycon.scope);

            byte[] responsebytes = wc.UploadValues(URL, "POST", reqparm);
            string responsebody = Encoding.UTF8.GetString(responsebytes);
            HttpContext.Current.Response.Write(responsebody);
        }
4

0 回答 0