HttpPost,MD5,Base64等介面調用中會用到的方法

來源:互聯網
上載者:User

標籤:

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;    }}

 

HttpPost,MD5,Base64等介面調用中會用到的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.