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

时间:2023-03-09 22:12:57
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;
}