HttpPost,MD5,Base64等接口调用中会用到的方法

HttpPost调用方法:

//url: 接口地址,param:类似key1=value1&key2=value2字符串
public static string WebRequestPost(string url, string param)
{
    string strResult = "";
    HttpWebRequest request = null;
    HttpWebResponse response = null;
    Stream stream = null;
    StreamReader reader = null;
    try
    {
        if (url.Contains("https"))
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
            request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
        }
        else
        {
            request = (HttpWebRequest)WebRequest.Create(url);
        }
        request.ServicePoint.Expect100Continue = false;
        request.Method = "POST";
        request.KeepAlive = true;
        request.Timeout = 100 * 1000;
        request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
        
        //把数组转换成流中所需字节数组类型
        byte[] bytes = Encoding.UTF8.GetBytes(param);
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(bytes, 0, bytes.Length);
        requestStream.Close();//释放
        
        //发送POST数据请求服务器
        response = (HttpWebResponse)request.GetResponse();
        Encoding encoding = System.Text.Encoding.UTF8;
        if (!string.IsNullOrEmpty(response.CharacterSet))
        {
            encoding = Encoding.GetEncoding(response.CharacterSet);
        }
        
        //获取服务器返回信息
        stream = response.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        strResult = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
        strResult = "报错:" + ex.Message;
    }
    finally
    {
        reader.Close();
        stream.Close();
        response.Close();
    }
    return strResult;
}

生成类似key1=value1&key2=value2字符串方法(按照key值大小进行排序):

1.传入Dictionary

private static string BuildPostData(IDictionary<string, string> parameters)
{
    StringBuilder builder = new StringBuilder();
    bool flag = false;
    IEnumerator<KeyValuePair<string, string>> enumerator = parameters.GetEnumerator();
    while (enumerator.MoveNext())
    {
        KeyValuePair<string, string> current = enumerator.Current;
        string key = current.Key;
        string str2 = current.Value;
        if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(str2))
        {
            if (flag)
            {
                builder.Append("&");
            }
            builder.Append(key);
            builder.Append("=");
            builder.Append(HttpUtility.UrlEncode(str2));
            flag = true;
        }
    }
    return builder.ToString();
}

2.传入List

public string GetParam(List<Param> paramList)
{
    List<Param> allparams = new List<Param>();
    foreach (Param param in paramList)
    {
        allparams.Add(param);
    }
    //冒泡排序,key按字母序从小到大
    for (int j = 1; j < allparams.Count; j++)
    {
        for (int i = 0; i < allparams.Count - j; i++)
        {
            if (String.Compare(allparams[i].getKey(), allparams[i + 1].getKey(), StringComparison.Ordinal) > 0)
            {
                Param temp = allparams[i];
                allparams[i] = allparams[i + 1];
                allparams[i + 1] = temp;
            }
        }
    }
    string source = "";
    string preKey = "";
    //把所有的键值依次放到一个字符串中,去掉重复的
    foreach (Param item in allparams)
    {
        string key = item.getKey();
        if (!preKey.Equals(key))
        {
            preKey = key;
            source += key + "=";
            source += item.getValue() + "&";
        }
    }
    return source.TrimEnd('&');
}

public class Param
{
    private string _key;
    private string _value;
    public Param() { }
    public Param(string key, string value)
    {
        _key = key;
        _value = value;
    }
    public string getKey()
    {
        return _key;
    }
    public string getValue()
    {
        return _value;
    }
    public void setKey(string key)
    {
        _key = key;
    }
    public void setValue(string value)
    {
        _value = value;
    }
}

//将paraList传入GetParam即可获得key1=value1&key2=value2的字符串
List<Param> paraList = new List<Param>();
paraList.Add(new Param("method", method));
paraList.Add(new Param("format", "json"));
paraList.Add(new Param("version", version));
paraList.Add(new Param("appid", appid));
paraList.Add(new Param("data", data));

MD5加密方法:

public static string MD5(string strInput)
{
    byte[] bytResult = Encoding.UTF8.GetBytes(strInput);
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] bytHash = md5.ComputeHash(bytResult);
    md5.Clear();
    string sTemp = "";
    for (int i = 0; i < bytHash.Length; i++)
    {
        //将字节数组元素转换为16进制字符串
        sTemp += bytHash[i].ToString("X2").ToLower();
    }
    return sTemp;
}

Base64加密方法:

public static string Base64(string source)
{
    byte[] bytes = Encoding.UTF8.GetBytes(source);
    try
    {
        return Convert.ToBase64String(bytes);
    }
    catch
    {
        return source;
    }
}
原文地址:https://www.cnblogs.com/zfylzl/p/5644957.html