如何在C#中发出POST请求

时间:2017-10-04 11:32:49

标签: c# asp.net .net visual-studio sharepoint

我试图创建一个帖子请求来从网站收集日期 我的要求应该是这样的:

POST /api/recent HTTP/1.1 
Host: domain.org 
Content-Type:application/x-www-form-urlencoded 
api_token=YOUR_TOKEN_VALUE

我尝试这个0错误但是没有工作:

private const string URL = " MY url";
private const string Parameters = "api_key= my key";
public static string HttpPost(string URI, string Parameters)
{
    System.Net.WebRequest req = System.Net.WebRequest.Create(URI);


    req.ContentType = "application/x-www-form-urlencoded";
    req.Method = "POST";

    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
    req.ContentLength = bytes.Length;
    System.IO.Stream os = req.GetRequestStream();
    os.Write(bytes, 0, bytes.Length); //Push it out there
    os.Close();
    System.Net.WebResponse resp = req.GetResponse();
    if (resp == null) return null;
    System.IO.StreamReader sr =
          new System.IO.StreamReader(resp.GetResponseStream());
    return sr.ReadToEnd().Trim();
}

1 个答案:

答案 0 :(得分:0)

尝试使用RestSharp

创建POST请求

GitHub上提供的源代码和一些教程,大量问题here on SO