C#发送post和get请求

C#发送post和get请求

private static Dictionary china_sms(string mobile, string param, DataRow row, out string strResult)
{
    strResult = string.Empty;

    Dictionary dic = new Dictionary();
    dic.Add("sid", row["sid"].ToString());
    dic.Add("token", row["token"].ToString());
    dic.Add("appid", row["appid"].ToString());
    dic.Add("templateid", row["refvar2"].ToString());
    dic.Add("param", param + ",5");
    dic.Add("mobile", mobile);

    string url = "http://open.ucpaas.com/ol/sms/sendsms";
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    req.Method = "POST";
    req.Accept = "application/json";
    req.ContentType = "application/json;charset=utf-8";

    #region 添加Post 参数
    StringBuilder builder = new StringBuilder();
    builder.Append(JsonConvertHelper.Dictionary2Json(dic));
    byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
    req.ContentLength = data.Length;
    using (Stream reqStream = req.GetRequestStream())
    {
        reqStream.Write(data, 0, data.Length);
        reqStream.Close();
    }
    #endregion
    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    Stream stream = resp.GetResponseStream();
    //获取响应内容  
    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
    {
        strResult = reader.ReadToEnd();
    }
    return JsonConvertHelper.Json2DictionaryObj(strResult);
}

private static string accessyou_sms(string mobile, string param, DataRow row, out string strResult)
{
    strResult = string.Empty;

    Dictionary dic = new Dictionary();
    dic.Add("accountno", row["usercode"].ToString());
    dic.Add("pwd", row["userpwd"].ToString());
    dic.Add("msg", param);
    dic.Add("phone", mobile);
    dic.Add("size", "l");

    string url = "http://api.accessyou.com/sms/sendsms-utf8.php?";

    #region 拼接GET参数
    string param_ = string.Empty;
    foreach (var item in dic.Keys)
    {
        param_ += item + "=" + System.Web.HttpUtility.UrlEncode(dic[item], Encoding.UTF8) + "&";
    }
    param_ = param_.Substring(0, param_.Length - 1);
    #endregion

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url + param_);
    req.Method = "GET";
    req.Accept = "application/json";
    req.ContentType = "application/json;charset=utf-8";
    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    Stream stream = resp.GetResponseStream();
    //获取响应内容  
    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
    {
        strResult = reader.ReadToEnd();
    }

    return strResult;
}

你可能感兴趣的:(实用,学习)