什么相当于.NET中的CURL

时间:2013-08-26 17:15:43

标签: .net

我需要连接到URL并从中下载数据。 api文档说明POST必须通过CURL进行,但我使用的是.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);
        }

0 个答案:

没有答案