首页 > 代码库 > 比较简单的Web请求(get/post)方法封装,调用网络接口时能用到
比较简单的Web请求(get/post)方法封装,调用网络接口时能用到
发送Web请求 ,GET请求和POST请求
/// <summary>
/// 发送GET请求/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string Webrequest(string url)
{
WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultCredentials;
wr.Method = "GET";
wr.ContentType = "application/x-www-form-urlencoded";
WebResponse response = wr.GetResponse();
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
/// <summary>
/// POST请求
/// </summary>
/// <param name="url"></param>
/// <param name="postdata">二进制后的参数</param>
/// <returns></returns>
public static string Webrequest(string url, byte[] postdata)
{
WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultCredentials;
wr.Method = "POST";
wr.ContentType = "application/x-www-form-urlencoded";
wr.ContentLength = postdata.Length;
Stream sw = wr.GetRequestStream();
sw.Write(postdata, 0, postdata.Length);
sw.Close();
WebResponse response = wr.GetResponse();
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream, Encoding.Default);
// Read the content.
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
比较简单的Web请求(get/post)方法封装,调用网络接口时能用到
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。