C# 带参访问接口,WebClient方式
http://www.cnblogs.com/cang12138/p/5896187.html
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); //创建WebRequest HttpWebRequest 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();


浙公网安备 33010602011771号