public string DoPost(string url, string data)
{
    HttpWebRequest req = GetWebRequest(url, "POST");
    byte[] postData = Encoding.UTF8.GetBytes(data);
    Stream reqStream = req.GetRequestStream();
    reqStream.Write(postData, 0, postData.Length);
    reqStream.Close();
    HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
    Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
    return GetResponseAsString(rsp, encoding);
}

public HttpWebRequest GetWebRequest(string url, string method)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    req.ServicePoint.Expect100Continue = false;
    req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
    req.ContentType = "text/json";
    req.Method = method;
    req.KeepAlive = true;
    req.UserAgent = "guanyisoft";
    req.Timeout = 1000000;
    req.Proxy = null;
    return req;
}

public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
    StringBuilder result = new StringBuilder();
    Stream stream = null;
    StreamReader reader = null;
    try
    {
        // 以字符流的方式读取HTTP响应
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        // 每次读取不大于256个字符,并写入字符串
        char[] buffer = new char[256];
        int readBytes = 0;
        while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
        {
            result.Append(buffer, 0, readBytes);
        }
    }
    finally
    {
        // 释放资源
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
    }

    return result.ToString();
}

相关文章:

  • 2021-07-05
  • 2021-11-12
  • 2022-12-23
  • 2022-12-23
  • 2021-09-18
  • 2021-10-11
  • 2022-02-25
猜你喜欢
  • 2021-03-31
  • 2021-12-23
  • 2022-12-23
  • 2021-12-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案