zoukankan      html  css  js  c++  java
  • HTTP请求

    public static string DoPost(string url, IDictionary<string, string> parameters)
    {
    HttpWebRequest req = GetWebRequest(url, "POST");
    req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

    byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters));
    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 static HttpWebRequest GetWebRequest(string url, string method)
    {
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    req.ServicePoint.Expect100Continue = false;
    req.Method = method;
    req.KeepAlive = true;
    req.UserAgent = "Top4Net";
    req.Timeout = 1000 * 100;
    return req;
    }
    /// <summary>
    /// 把响应流转换为文本。
    /// </summary>
    /// <param name="rsp">响应流对象</param>
    /// <param name="encoding">编码方式</param>
    /// <returns>响应文本</returns>
    public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
    {
    Stream stream = null;
    StreamReader reader = null;

    try
    {
    // 以字符流的方式读取HTTP响应
    stream = rsp.GetResponseStream();
    reader = new StreamReader(stream, encoding);
    return reader.ReadToEnd();
    }
    finally
    {
    // 释放资源
    if (reader != null) reader.Close();
    if (stream != null) stream.Close();
    if (rsp != null) rsp.Close();
    }
    }

    /// <summary>
    /// 组装普通文本请求参数。
    /// </summary>
    /// <param name="parameters">Key-Value形式请求参数字典</param>
    /// <returns>URL编码后的请求数据</returns>
    public static string BuildQuery(IDictionary<string, string> parameters)
    {
    StringBuilder postData = new StringBuilder();
    bool hasParam = false;

    IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
    while (dem.MoveNext())
    {
    string name = dem.Current.Key;
    string value = dem.Current.Value;
    // 忽略参数名或参数值为空的参数
    if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
    {
    if (hasParam)
    {
    postData.Append("&");
    }

    postData.Append(name);
    postData.Append("=");
    postData.Append(Uri.EscapeDataString(value));
    hasParam = true;
    }
    }
    return postData.ToString();
    }

  • 相关阅读:
    Delphi实现文件关联
    用Delphi实现文件关联
    Delphi 7使用自定义图标关联文件类型
    redux-form的学习笔记
    妙用 `package.json` 快速 `import` 文件(夹)
    【webpack2】-- 入门与解析
    黑科技:CSS定制多行省略
    DOM操作和样式操作库的封装
    webstorm 2016 激活破解
    js/jq仿window文件夹框选操作插件
  • 原文地址:https://www.cnblogs.com/xiguanjiandan/p/2729514.html
Copyright © 2011-2022 走看看