• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#发送请求获得响应

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

两种封装方法:

View Code
#region 发送Http请求,获取返回结果
/// <summary>
/// 发送http请求,获取响应( Send HttpRequest and Get HttpResponse)
/// </summary>
/// <param name="RequestUrl">请求地址</param>
/// <param name="Params">http请求参数</param>
/// <returns>响应内容</returns>
private string SendRequestGetResponse(string RequestUrl, string Params)
{
HttpWebRequest HWRequest = null;
string NewUrl = string.Empty;
string RetCode = string.Empty;

try
{
HWRequest = (HttpWebRequest)WebRequest.Create(RequestUrl);
HWRequest.KeepAlive = true;
HWRequest.Timeout = 30000;
HWRequest.Method = "POST";
HWRequest.ContentType = "application/x-www-form-urlencoded";

HttpWebResponse HWResponse = null;
byte[] reqParams = System.Text.Encoding.ASCII.GetBytes(Params);
Stream st = HWRequest.GetRequestStream();
st.Write(reqParams, 0, reqParams.Length);
st.Flush();
st.Close();

HWResponse = (HttpWebResponse)HWRequest.GetResponse();
Stream ResSt = HWResponse.GetResponseStream();
StreamReader sr = new StreamReader(ResSt, System.Text.Encoding.UTF8);
RetCode = sr.ReadToEnd();
ResSt.Close();
ResSt.Close();
HWResponse.Close();
ResSt.Dispose();
sr.Dispose();
st.Dispose();
}
catch
{
RetCode = string.Empty;
}

return RetCode;
}
#endregion


#region 发送HTTP请求,获得响应
/// <summary>
/// 发送请求返回字符串
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="para">请求字符串</param>
/// <param name="method">请求方式GET或POST</param>
/// <returns></returns>
private string SendRequestBackStr(string url, string para, string method)
{
string strResult = "";
if (url == null || url == "")
return null;
if (method == null || method == "")
method = "GET";
#region GET方式
if (method.ToUpper() == "GET")
{
try
{
HttpWebRequest wrq = (HttpWebRequest)WebRequest.Create(url + para);
wrq.AllowAutoRedirect = false;
HttpWebResponse wrp = (HttpWebResponse)wrq.GetResponse();
if (((int)wrp.StatusCode) == 302)
{
url = wrp.Headers["Location"];
if (url.IndexOf("?") < 0)
{
para = "&" + para.Substring(1, para.Length - 1);
}
wrq = (HttpWebRequest)WebRequest.Create(url + para);
}
System.IO.StreamReader sr = new System.IO.StreamReader(wrp.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));

strResult = sr.ReadToEnd();
}
catch (Exception ex)
{
return ex.Message;
}
}
#endregion
#region POST方式
if (method.ToUpper() == "POST")
{
if (para.Length > 0 && para.IndexOf('?') == 0)
{
para = para.Substring(1);
}

WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
StringBuilder UrlEncoded = new StringBuilder();
Char[] reserved = { '?', '=', '&' };
byte[] SomeBytes = null;
if (para != null)
{
int i = 0, j;
while (i < para.Length)
{
j = para.IndexOfAny(reserved, i);
if (j == -1)
{
UrlEncoded.Append(HttpUtility.UrlEncode(para.Substring(i, para.Length - i), System.Text.Encoding.GetEncoding("GB2312")));
break;
}
UrlEncoded.Append(HttpUtility.UrlEncode(para.Substring(i, j - i), System.Text.Encoding.GetEncoding("GB2312")));
UrlEncoded.Append(para.Substring(j, 1));
i = j + 1;
}
SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString());
req.ContentLength = SomeBytes.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
}
else
{
req.ContentLength = 0;
}
try
{
WebResponse result = req.GetResponse();
Stream ReceiveStream = result.GetResponseStream();

Byte[] read = new Byte[512];
int bytes = ReceiveStream.Read(read, 0, 512);

while (bytes > 0)
{
// 注意:
// 下面假定响应使用 UTF-8 作为编码方式。
// 如果内容以 ANSI 代码页形式(例如,932)发送,则使用类似下面的语句:
// Encoding encode = System.Text.Encoding.GetEncoding("shift-jis");
Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
strResult += encode.GetString(read, 0, bytes);
bytes = ReceiveStream.Read(read, 0, 512);
}

return strResult;
}
catch (Exception ex)
{
return ex.Message;
}
}
#endregion
return strResult;
}
#endregion

第一种考虑到请求方式Method,get 或者 Post,第二段代码可根据情况删减。post时需要用stream流传递请求参数,get则不需要。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
c#免注册调用大漠插件100%完美识别文字发布时间:2022-07-10
下一篇:
C#中Typeof是什么?和GetType有什么关系?发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap