• 00
  • :
  • 00
  • :
  • 00

C# POST与Get数据

引用DLL

 

普通Get数据和Post数据

 

 1    public static string Get(string URL)
 2         {
 3             String ReCode = string.Empty;
 4             try
 5             {
 6                 HttpWebRequest wNetr = (HttpWebRequest)HttpWebRequest.Create(URL);
 7                 HttpWebResponse wNetp = (HttpWebResponse)wNetr.GetResponse();
 8                 wNetr.ContentType = "text/html";
 9                 wNetr.Method = "Get";
10                 Stream Streams = wNetp.GetResponseStream();
11                 StreamReader Reads = new StreamReader(Streams, Encoding.UTF8);
12                 ReCode = Reads.ReadToEnd();
13 
14                 //封闭临时不实用的资料 
15                 Reads.Dispose();
16                 Streams.Dispose();
17                 wNetp.Close();
18             }
19             catch (Exception ex) { throw ex; }
20 
21             return ReCode;
22 
23         }
24 
25         public static string Post(string url, string data)
26         {
27             string returnData = null;
28             try
29             {
30                 //byte[] buffer = Encoding.UTF8.GetBytes(data);
31                 //HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
32                 //webReq.Method = "POST";
33                 //webReq.ContentType = "application/x-www-form-urlencoded";
34                 //webReq.ContentLength = buffer.Length;
35                 //Stream postData = webReq.GetRequestStream();
36                 //webReq.Timeout = 99999999;
37                 ////webReq.ReadWriteTimeout = 99999999;
38                 //postData.Write(buffer, 0, buffer.Length);
39                 //postData.Close();
40                 //HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
41                 //Stream answer = webResp.GetResponseStream();
42                 //StreamReader answerData = new StreamReader(answer);
43                 //returnData = answerData.ReadToEnd();
44 
45                 string strURL = url;
46                 System.Net.HttpWebRequest request;
47                 request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
48                 request.Method = "POST";
49                 request.ContentType = "application/json;charset=UTF-8";
50                 string paraUrlCoded = data;
51                 byte[] payload;
52                 payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
53                 request.ContentLength = payload.Length;
54                 Stream writer = request.GetRequestStream();
55                 writer.Write(payload, 0, payload.Length);
56                 writer.Close();
57                 System.Net.HttpWebResponse response;
58                 response = (System.Net.HttpWebResponse)request.GetResponse();
59                 System.IO.Stream s;
60                 s = response.GetResponseStream();
61                 string StrDate = "";
62                 string strValue = "";
63                 StreamReader Reader = new StreamReader(s, Encoding.UTF8);
64                 while ((StrDate = Reader.ReadLine()) != null)
65                 {
66                     strValue += StrDate + "\r\n";
67                 }
68                 returnData = strValue;
69             }
70             catch
71             {
72                 return "获取错误";
73             }
74             return returnData.Trim() + "\n";
75         }
76         /// <summary>
77         /// 将json数据反序列化为Dictionary
78         /// </summary>
79         /// <param name="jsonData">json数据</param>
80         /// <returns></returns>
81         public static Dictionary<string, object> JsonToDictionary(string jsonData)
82         {
83             //实例化JavaScriptSerializer类的新实例。。。需要添加 System.Web.Extensions引用
84             JavaScriptSerializer jss = new JavaScriptSerializer();
85             try
86             {
87                 //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
88                 return jss.Deserialize<Dictionary<string, object>>(jsonData);
89             }
90             catch (Exception ex)
91             {
92                 throw new Exception(ex.Message);
93             }
94         }

HTTPS POST

class ProgramTest
{
    static void Main(string[] args)
    {
        string url = "https://www.test.com";
        string result = PostUrl(url, "key=123"); // key=4da4193e-384b-44d8-8a7f-2dd8b076d784
        Console.WriteLine(result);
        Console.WriteLine("OVER");
        Console.ReadLine();
    }

    private static string PostUrl(string url, string postData)
    {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request.ProtocolVersion = HttpVersion.Version11;
         // 这里设置了协议类型。
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
            request.KeepAlive = false;
            ServicePointManager.CheckCertificateRevocationList = true;
            ServicePointManager.DefaultConnectionLimit = 100;
            ServicePointManager.Expect100Continue = false;
        }
        request.Method = "POST";    //使用get方式发送数据
        request.ContentType = "application/x-www-form-urlencoded";
        request.Referer = null;
        request.AllowAutoRedirect = true;
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        request.Accept = "*/*";

        byte[] data = Encoding.UTF8.GetBytes(postData);
        Stream newStream = request.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();

        //获取网页响应结果
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream stream = response.GetResponseStream();
        //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        string result = string.Empty;
        using (StreamReader sr = new StreamReader(stream))
        {
            result = sr.ReadToEnd();
        }

        return result;
    }

    private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        return true; //总是接受  
    }
}

 

 

附.另外一个Post

public void Post()
{
 var d = new SendNews();
            d.touser = touser;
            d.agentid = "7";
            d.Description = wxmsg;

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:47870/");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = client.PostAsJsonAsync("api/SendMsg/SendNews", d).Result; 
}


   public class SendNews 
        {
            /// <summary>
            /// UserID列表(消息接收者,多个接收者用‘|’分隔)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送 
            /// </summary>
            public string touser { get; set; }
            /// <summary>
            /// PartyID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数
            /// </summary>
            public string toparty { get; set; }
            /// <summary>
            /// TagID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数 
            /// </summary>
            public string totag { get; set; }
            /// <summary>
            /// 消息类型
            /// </summary>
            public string msgtype { get; set; }
            /// <summary>
            /// 企业应用的id,整型。可在应用的设置页面查看 
            /// </summary>
            public string agentid { get; set; }

            /// <summary>
            /// 表示是否是保密消息,0表示否,1表示是,默认0 
            /// </summary>
            public string safe { get; set; }


            /// <summary>
            /// 文章标题
            /// </summary>
            public string Title { get; set; }
            /// <summary>
            /// 文章描述
            /// </summary>
            public string Description { get; set; }
            /// <summary>
            /// 图片链接,支持JPG、PNG格式,较好的效果为大图360*200,小图200*200
            /// </summary>
            public string PicUrl { get; set; }
            /// <summary>
            /// 点击图文消息跳转链接
            /// </summary>
            public string Url { get; set; }
        }

 

键值对提交

        //重点!! 成功 利用Webclient Post 按字段的方式提交每个字段的内容给服务器端 
        public string WebClientPost(string url, System.Collections.Specialized.NameValueCollection PostVars)
        {
            try
            {
                System.Net.WebClient WebClientObj = new System.Net.WebClient();
                byte[] byRemoteInfo = WebClientObj.UploadValues(url, "POST", PostVars);
                //下面都没用啦,就上面一句话就可以了
                string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo);
                return sRemoteInfo;

            }
            catch
            {
                return "";
            }
        }

        public void test()
        {
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
            PostVars.Add("test", "value");
            PostVars.Add("cmd", "value");
            PostVars.Add("token", "value");
            WebClientPost("url", PostVars);
        }

 

posted @ 2015-06-10 15:52  Garson_Zhang  阅读(552)  评论(0编辑  收藏  举报