当前位置: 首页 > news >正文

.NET中winform传递参数至Url并获得返回值或文件

在winform里面调用URL并传递参数主要使用HttpWebRequest对象,分为两种形式post和get,个人感觉就是模拟了浏览器,

1.post方法:

/// <summary>
        /// 使用post方法,调用短信接口
        /// < /summary>
        /// <param  name="PhoneNumber"></param>
        /// <param  name="SmsContent"></param>
        /// <param  name="PhoneNumberType"></param>
        /// <param  name="SmsUser"></param>
        private void  CallMsgCenterToSendMsgPost(string PhoneNumber, string SmsContent, string PhoneNumberType, string SmsUser)
        {
            string  formUrl =  ConfigurationSettings.AppSettings["formUrl"].ToString().Trim();//url地址
            string formData = "PhoneNumber=" + PhoneNumber + "&SmsContent="  +SmsContent + "&PhoneNumberType=" + PhoneNumberType +  "&SmsUser=" + SmsUser + "";
            CookieContainer  cookieContainer = new CookieContainer();
            // 将提交的字符串数据转换成字节数组
            byte[] postData =  Encoding.UTF8.GetBytes(formData);
           
            // 设置提交的相关参数
            HttpWebRequest request =  WebRequest.Create(formUrl) as HttpWebRequest;
            Encoding  myEncoding = Encoding.GetEncoding("gb2312"); 
             request.Method = "POST";
            request.KeepAlive = false;
            request.AllowAutoRedirect = true;
            request.ContentType =  "application/x-www-form-urlencoded";
            request.UserAgent =  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR  2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR  3.0.4506.2152; .NET CLR 3.5.30729)";
             request.CookieContainer = cookieContainer;
             request.ContentLength = postData.Length;

// 提交请求数据
            System.IO.Stream outputStream =  request.GetRequestStream();
            outputStream.Write(postData,  0, postData.Length);
            outputStream.Close();

HttpWebResponse response;
            Stream responseStream;
            StreamReader reader;
            string srcString;
             response = request.GetResponse() as HttpWebResponse;
             responseStream = response.GetResponseStream();
            reader =  new System.IO.StreamReader(responseStream, Encoding.UTF8);
            srcString = reader.ReadToEnd();
            reader.Close();
        }

2,get方法

/// <summary>
        /// 使用get方法
        /// < /summary>
        /// <param  name="PhoneNumber"></param>
        /// <param  name="SmsContent"></param>
        /// <param  name="PhoneNumberType"></param>
        /// <param  name="SmsUser"></param>
        private void  CallMsgCenterToSendMsgGet(string PhoneNumber, string SmsContent, string  PhoneNumberType, string SmsUser)
        {
            string  formUrl =  ConfigurationSettings.AppSettings["formUrl"].ToString().Trim();
            string formData = "PhoneNumber=" + HttpUtility.UrlEncode(PhoneNumber) + "&SmsContent=" + HttpUtility.UrlEncode(SmsContent) +  "&PhoneNumberType=" + HttpUtility.UrlEncode(PhoneNumberType) +  "&SmsUser=" + HttpUtility.UrlEncode(SmsUser) + "";
             CookieContainer cookieContainer = new CookieContainer();

formUrl = formUrl + "?" + formData;
            // 设置提交的相关参数
            HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest;
         
            request.Method = "GET";
             request.KeepAlive = false;
            request.AllowAutoRedirect =  true;
            request.ContentType =  "application/x-www-form-urlencoded";
            request.UserAgent =  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR  2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR  3.0.4506.2152; .NET CLR 3.5.30729)";
             request.CookieContainer = cookieContainer;

HttpWebResponse SendSMSResponse =  (HttpWebResponse)request.GetResponse();

StreamReader SendSMSResponseStream = new  StreamReader(SendSMSResponse.GetResponseStream());

string strRespone = SendSMSResponseStream.ReadToEnd();

SendSMSResponse.Close();
             SendSMSResponseStream.Close();  
        }

3,调用起来都比较简单的,主要是在传递参数的过程中注意中文的处理,否则会变为乱码,获取返回值当然就使用HttpWebResponse对象了

例子

                 //string strImageURL = "http://192.168.0.72:8888/SealCenter/SEAL_FILE_DOWN.do?";
                string strImageURL = url;// "http://192.168.0.72:8888/SealCenter/SEAL_FILE_DOWN.do?";
                strImageURL = strImageURL + "SERIAL=" + this.MD5String(cerKey) + "&TYPE=" + this.cmbSPECIALTYPE.SelectedValue + "&CITYCODE=" + this.cmbZone.SelectedValue;
               
                System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strImageURL);
                webRequest.Method = "GET";
                webRequest.KeepAlive = false;
                webRequest.AllowAutoRedirect = true;
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                //webRequest.CookieContainer = cookieContainer;
                System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();

                System.IO.Stream s = webResponse.GetResponseStream();

                List<byte> list = new List<byte>();
                while (true)
                {
                    int data = s.ReadByte();
                    if (data == -1)
                        break;
                    else
                    {
                        byte b = (byte)data;
                        list.Add(b);
                    }
                }
                byte[] bb = list.ToArray();
                System.IO.File.WriteAllBytes(Path, bb); //Path保存的文件 得事先知道文件的后缀
                s.Close();

方法2示例代码:
--------------
string strImageURL = "http://192.168.0.1:88/VDirA/images/1.jpg";

System.Net.WebClient webClient = new  System.Net.WebClient();
webClient.DownloadFile(strImageURL, @"D:/1.jpg");

方法3示例代码:
--------------
string strImageURL = "http://192.168.0.1:88/VDirA/images/1.jpg";

System.Net.HttpWebRequest webRequest =  (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strImageURL);
webRequest.Method = "GET";
System.Net.HttpWebResponse webResponse =  (System.Net.HttpWebResponse)webRequest.GetResponse();

System.IO.Stream s =  webResponse.GetResponseStream();

List<byte> list = new List<byte>();
while (true)
{
    int data = s.ReadByte();
    if (data == -1)
        break;
    else
    {
        byte b = (byte)data;
        list.Add(b);
    }
}
byte[] bb = list.ToArray();
System.IO.File.WriteAllBytes("C://1.jpg", bb);
s.Close();

 

 

相关文章:

  • httpwebresponse 异步: request.BeginGetRequestStream 报错! 无法发送具有此谓词类型的内容正文。
  • WinForm 使用 HttpUtility
  • 支持中文的URLDecode ASP函数
  • IIS应用程序池w3wp.exe CPU 占用100% 分析软件,找出具体有问题的ASP程序URL
  • Ubuntu开启ssh服务
  • mysql in和exists性能比较和使用
  • 诸葛亮写给后代的一封信,只有86个字
  • Mysql复制表结构、表数据
  • mysql中如何设置默认时间为当前时间
  • linux zip 压缩命令 解压命令 unzip
  • 通用CSS Hack
  • 解决w3wp.exe内存占用问题
  • ASP.NET读取ASP设置的Cookie
  • Asp操作Cookies(设置[赋值]、读取、删除[设置过期时间])
  • 判断客户浏览器是否支持cookie
  • 「译」Node.js Streams 基础
  • 3.7、@ResponseBody 和 @RestController
  • C学习-枚举(九)
  • HTTP请求重发
  • Java教程_软件开发基础
  • Java应用性能调优
  • java中的hashCode
  • niucms就是以城市为分割单位,在上面 小区/乡村/同城论坛+58+团购
  • Python代码面试必读 - Data Structures and Algorithms in Python
  • Spring框架之我见(三)——IOC、AOP
  • - 概述 - 《设计模式(极简c++版)》
  • 蓝海存储开关机注意事项总结
  • 排序(1):冒泡排序
  • 使用docker-compose进行多节点部署
  • 通过npm或yarn自动生成vue组件
  • 微信小程序上拉加载:onReachBottom详解+设置触发距离
  • 项目实战-Api的解决方案
  • 新版博客前端前瞻
  • 一起来学SpringBoot | 第三篇:SpringBoot日志配置
  • Android开发者必备:推荐一款助力开发的开源APP
  • MyCAT水平分库
  • 好程序员web前端教程分享CSS不同元素margin的计算 ...
  • 支付宝花15年解决的这个问题,顶得上做出十个支付宝 ...
  • # centos7下FFmpeg环境部署记录
  • $(document).ready(function(){}), $().ready(function(){})和$(function(){})三者区别
  • (C++17) optional的使用
  • (附源码)apringboot计算机专业大学生就业指南 毕业设计061355
  • (附源码)springboot掌上博客系统 毕业设计063131
  • (黑马出品_高级篇_01)SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式
  • (转)linux自定义开机启动服务和chkconfig使用方法
  • (转)socket Aio demo
  • * 论文笔记 【Wide Deep Learning for Recommender Systems】
  • **python多态
  • .bashrc在哪里,alias妙用
  • .NET 材料检测系统崩溃分析
  • .net 获取url的方法
  • .Net 知识杂记
  • .NET(C#) Internals: as a developer, .net framework in my eyes
  • .NET/C# 解压 Zip 文件时出现异常:System.IO.InvalidDataException: 找不到中央目录结尾记录。
  • .net专家(高海东的专栏)