C# 带参访问接口,WebClient方式

来源:互联网 发布:淘宝微信返利机器人 编辑:程序博客网 时间:2024/05/22 10:29

1、当参数的数据较大时。WebClient同步。

复制代码
//实例化
WebClient client = new WebClient();
//
地址string path = "http://127.0.0.1/a/b";//数据较大的参数string datastr = "id=" + System.Web.HttpUtility.UrlEncode(ids);//参数转流byte[] bytearray = Encoding.UTF8.GetBytes(datastr);//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//长度client.Headers.Add("ContentLength", bytearray.Length.ToString());//上传,post方式,并接收返回数据(这是同步,需要等待接收返回值)byte[] responseData = client.UploadData(path, "POST", bytearray);//释放client.Dispose();//处理返回数据(一般用json)string srcString = Encoding.UTF8.GetString(responseData);
复制代码
回到顶部

2、当参数的数据较大时。WebClient异步(接上面的代码)。

复制代码
//绑定事件,为了获取返回值client.UploadDataCompleted += new UploadDataCompletedEventHandler(UploadDataCallback2);//这里是url地址Uri uri = new Uri(url);//异步post提交,不用等待。client.UploadDataAsync(uri, "POST", bytearray);//接收返回值的方法public static void UploadDataCallback2(Object sender, UploadDataCompletedEventArgs e){    //接收返回值    byte[] data = (byte[])e.Result;    //转码    string reply = Encoding.UTF8.GetString(data);    //打印日志    LogResult("返回数据:" + reply + "\n");}
复制代码
回到顶部

3、当参数的数据正常时

复制代码
//地址string url = "http://127.0.0.1:8080/action?id=" + id + "";//实例化WebClient client = new WebClient();//上传并接收数据Byte[] responseData = client.DownloadData(url);//接收返回的json的流数据,并转码string srcString = Encoding.UTF8.GetString(responseData);
复制代码
回到顶部

4、超时时间设置

复制代码
//需要新写个类继承WebClient,并重写//然后实例化,就可以设置超时时间了。例:WebClient webClient = new WebDownload();/// <summary>/// WebClient 超时设置/// </summary>public class WebDownload : WebClient{    private int _timeout;    // 超时时间(毫秒)    public int Timeout    {        get        {            return _timeout;        }        set        {            _timeout = value;        }    }    public WebDownload()    {
//设置时间
this._timeout = 60000000; } public WebDownload(int timeout) { this._timeout = timeout; } protected override WebRequest GetWebRequest(Uri address) { var result = base.GetWebRequest(address); result.Timeout = this._timeout; return result; }}
复制代码
回到顶部

5、WebRequest方式

复制代码
//地址string url = "http://127.0.0.1/a/b?pro=" + pro;//传的参数string datastr1 = "id=" + System.Web.HttpUtility.UrlEncode(ids);//转成字节byte[] bytearray1 = Encoding.UTF8.GetBytes(datastr1);//创建WebRequestHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);//POST方式webrequest.Method = "POST";// <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)webrequest.ContentType = "application/x-www-form-urlencoded";//获取字节数webrequest.ContentLength = Encoding.UTF8.GetByteCount(datastr1);//获取用于写入请求数据的 System.IO.Stream 对象Stream webstream = webrequest.GetRequestStream();//向当前流中写入字节序列,并将此流中的当前位置提升写入的字节数。webstream.Write(bytearray1, 0, bytearray1.Length);//获取返回数据HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();//转码StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);//返回的结果string ret = sr.ReadToEnd();//关闭sr.Close();response.Close();webstream.Close();

复制代码

转载自 http://www.cnblogs.com/cang12138/p/5896187.html


阅读全文
0 0
原创粉丝点击