c# get 和post 请求 实战

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace iLogisticBase.Common.Setting.Dal
{
    public class vUnLoCodeBLL
    {
        public static string URL = string.Empty;

        public vUnLoCodeBLL()
        {
            URL = "";
        }

        /// <summary>
        /// 发送http post请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="parameters">查询参数集合</param>
        /// <returns></returns>
        public HttpWebResponse CreatePostHttpResponse(IDictionary<string, string> parameters)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;//创建请求对象
                request.Method = "POST";//请求方式
                request.ContentType = "application/x-www-form-urlencoded";//链接类型                                                                      //构造查询字符串
                if (!(parameters == null || parameters.Count == 0))
                {
                    StringBuilder buffer = new StringBuilder();
                    bool first = true;
                    foreach (string key in parameters.Keys)
                    {
                        if (!first)
                        {
                            buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, parameters[key]);
                            first = false;
                        }
                    }
                    byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                    //写入请求流
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                return request.GetResponse() as HttpWebResponse;
            }
            catch (Exception)
            {

                return null;
            }
        }

        /// <summary>
        /// 发送http Get请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public HttpWebResponse CreateGetHttpResponse(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";//链接类型
            return request.GetResponse() as HttpWebResponse;
        }
        /// <summary>
        /// 从HttpWebResponse对象中提取响应的数据转换为字符串
        /// </summary>
        /// <param name="webresponse"></param>
        /// <returns></returns>
        public string GetResponseString(HttpWebResponse webresponse)
        {
            try
            {
                using (Stream s = webresponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(s, Encoding.UTF8);
                    return reader.ReadToEnd();
                }
            }
            catch (Exception)
            {

                return null;
            }
        }


        //post请求并调用

        //        Dictionary<string, string> dic = new Dictionary<string, string>();
        //        dic.Add("id", "4");
        //textBox1.Text = GetResponseString(CreatePostHttpResponse("https://www.baidu.com/", dic));
        get请求并调用

        //textBox3.Text = GetResponseString(CreateGetHttpResponse("https://i.cnblogs.com/EditPosts.aspx?opt=1"));

        private void get()
        {
            //string URL = "http://192.168.1.47:60002/api/Port/GetData?";

            //var data = new vUnLoCode();
            //StringBuilder stringBuilder = new StringBuilder();
            //foreach (var item in typeof(vUnLoCode).GetProperties())
            //{
            //    stringBuilder.Append($"{item.Name}={item.GetValue(data, null)}&");
            //}

            //System.Net.WebClient webClient = new System.Net.WebClient();          
            //var v = webClient.DownloadString(URL+stringBuilder.ToString());
        }

    }
}
 

//调用

 

Dictionary<string, string> dics = new Dictionary<string, string>();
            foreach (var item in typeof(vUnLoCodeDTO).GetProperties())
            {
                if (item.GetValue(_queryvUnLoCodeDTO, null) != null && item.GetValue(_queryvUnLoCodeDTO, null).ToString() != "")
                {
                    dics.Add(item.Name, item.GetValue(_queryvUnLoCodeDTO, null).ToString());
                }
            }
            if (dics.Count > 0)
            {
                string result = bll.GetResponseString(bll.CreatePostHttpResponse(dics));
                if (result != null)
                {
                    List<vUnLoCode> vUnLoCodes = bll.Serializer(result);
                    if (vUnLoCodes != null)
                    {
                        gcPortCode.DataSource = vUnLoCodes;
                        gcPortCode.Focus();
                    }
                    else
                    {
                        MessageBox.Show("请检查输入条件是否正确");
                    }
                }
            }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Collections; using System.IO; using System.Text.RegularExpressions; using RE = System.Text.RegularExpressions.Regex; using System.Security.Cryptography.X509Certificates; /*************************************************************************************************************************************************** * *文件名:HttpProc.cs * *创建人:HeDaode * *日 期:2007.09.01 * *描 述:实现HTTP协议中的GET、POST请求 * *使 用:HttpProc.WebClient client = new HttpProc.WebClient(); client.Encoding = System.Text.Encoding.Default;//默认编码方式,根据需要设置其他类型 client.OpenRead("http://www.baidu.com");//普通get请求 MessageBox.Show(client.RespHtml);//获取返回的网页源代码 client.DownloadFile("http://www.codepub.com/upload/163album.rar",@"C:\163album.rar");//下载文件 client.OpenRead("http://passport.baidu.com/?login","username=zhangsan&password=123456");//提交表单,此处是登录百度的示例 client.UploadFile("http://hiup.baidu.com/zhangsan/upload", @"file1=D:\1.mp3");//上传文件 client.UploadFile("http://hiup.baidu.com/zhangsan/upload", "folder=myfolder&size=4003550",@"file1=D:\1.mp3");//提交含文本域和文件域的表单 *****************************************************************************************************************************************************/ namespace HttpProc { /// ///上传事件委托 /// /// /// public delegate void WebClientUploadEvent(object sender, HttpProc.UploadEventArgs e); /// ///下载事件委托 /// /// /// public delegate void WebClientDownloadEvent(object sender, HttpProc.DownloadEventArgs e); /// ///上传事件参数 /// public struct UploadEventArgs { /// ///上传数据总大小 ///
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勿在浮沙筑高台

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值