C# WebClient 实现上传下载网络资源

 

下载数据

WebClient wc = new WebClient();
1 string str= wc.DownloadString("地址");//直接下载字符串

2 wc.DownloadFile("addredd", "fileName");//下载文件 并指定下载到的地址

3  byte[] b=wc.DownloadData("address")//直接返回一个二进制数组 然后进行转换

wc.Dispose();

上传数据

    string postString = "arg1=a&arg2=b";//这里即为传递的参数,可以用工具抓包分析,也可以自己分析,主要是form里面每一个name都要加进来     byte[] postData = Encoding.UTF8.GetBytes(postString);//编码,尤其是汉字,事先要看下抓取网页的编码方式 

    WebClient webClient = new WebClient();  

 

   webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可                 byte[] responseData = webClient.UploadData("url", "POST", postData);//得到返回字符流  string srcString = Encoding.UTF8.GetString(responseData);//解码 

 

 

附带一些事例代码:

public static string PostHttp(string url, string body, string contentType)//通过HttpWebRequest post请求url并得到返回数据
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

httpWebRequest.ContentType = contentType;
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = 20000;

byte[] btBodys = Encoding.UTF8.GetBytes(body);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());

string responseContent = streamReader.ReadToEnd();
httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort();
httpWebResponse.Close();

return responseContent;
}

public static string GetHttp(string url, HttpContext httpContext) //通过HttpWebRequest Get请求一个地址获取数据
{
string queryString = "?";

foreach (string key in httpContext.Request.QueryString.AllKeys)
{
queryString += key + "=" + httpContext.Request.QueryString[key] + "&";
}

queryString = queryString.Substring(0, queryString.Length - 1);

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);

httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Timeout = 20000;
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd();

httpWebResponse.Close();
streamReader.Close();

return responseContent;
}

转载于:https://www.cnblogs.com/lxtblogs/p/4784096.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值