C#-HTTP请求GET

public static string SendRequestUTF8(string url, string para, string method, int timeout, string ContentType, ref string Status, string Tag, string LogName)
{
    Status = "OK";
    string strResult = "";
    if (url == null || url == "")
	return null;
    if (method == null || method == "")
	method = "GET";
    // GET方式
    if (method.ToUpper() == "GET")
    {
	try
	{
	    System.GC.Collect();
	    //设置最大连接数
	    ServicePointManager.DefaultConnectionLimit = 200;
	    //设置https验证方式
	    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
	    {
		ServicePointManager.ServerCertificateValidationCallback =
			new RemoteCertificateValidationCallback(CheckValidationResult);
	    }
	    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
	    System.Net.WebRequest wrq = System.Net.WebRequest.Create(url + para);
	    wrq.Method = "GET";
	    if (timeout != 0)
	    {
		wrq.Timeout = timeout;
	    }
	    using (System.Net.WebResponse wrp = wrq.GetResponse())
	    {
		using (System.IO.StreamReader sr = new System.IO.StreamReader(wrp.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")))
		{
		    strResult = sr.ReadToEnd();
		    sr.Close();
		    sr.Dispose();
		}
		wrp.Close();
	    }
	    wrq.Abort();
	}
	catch (WebException ex)
	{
	    if (LogName != null)
	    {
		T9.Util.LogUtil.WriteLog("SendRequestUTF8-发生未知错误" + (Tag != null ? "[" + Tag + "]" : "") + ":\r\n" + ex.Message.ToString() + "\r\n报错详情:" + ex.StackTrace.ToString()
		   , LogName);
	    }
	    Status = ex.Status.ToString();
	    return ex.Message;
	}
	catch (Exception ex)
	{
	    if (LogName != null)
	    {
		T9.Util.LogUtil.WriteLog("SendRequestUTF8-发生未知错误" + (Tag != null ? "[" + Tag + "]" : "") + ":\r\n" + ex.Message.ToString() + "\r\n报错详情:" + ex.StackTrace.ToString()
		   , LogName);
	    }
	    Status = "T9_9999";
	    return ex.Message;
	}
    }
    // POST方式
    else if (method.ToUpper() == "POST")
    {
	try
	{
	    if (para.Length > 0 && para.IndexOf('?') == 0)
	    {
		para = para.Substring(1);
	    }
	    WebRequest req = WebRequest.Create(url);
	    req.Method = "POST";
	    if (timeout != 0)
	    {
		req.Timeout = timeout;
	    }//application/x-www-form-urlencoded
	    req.ContentType = string.IsNullOrWhiteSpace(ContentType) ? "application/x-www-form-urlencoded" : ContentType;
	    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
	    {
		ServicePointManager.ServerCertificateValidationCallback =
			new RemoteCertificateValidationCallback(CheckValidationResult);
	    }
	    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("utf-8")));
			break;
		    }
		    UrlEncoded.Append(HttpUtility.UrlEncode(para.Substring(i, j - i), System.Text.Encoding.GetEncoding("utf-8")));
		    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;
	    }
	    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
	    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("utf-8");
		strResult += encode.GetString(read, 0, bytes);
		bytes = ReceiveStream.Read(read, 0, 512);
	    }
	    return strResult;
	}
	catch (WebException ex)
	{
	    if (LogName != null)
	    {
		T9.Util.LogUtil.WriteLog("SendRequestUTF8-发生未知错误" + (Tag != null ? "[" + Tag + "]" : "") + ":\r\n" + ex.Message.ToString() + "\r\n报错详情:" + ex.StackTrace.ToString()
		   , LogName);
	    }
	    Status = ex.Status.ToString();
	    if (ex.Response != null)
	    {
		Stream ReceiveStream = ex.Response.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("utf-8");
		    strResult += encode.GetString(read, 0, bytes);
		    bytes = ReceiveStream.Read(read, 0, 512);
		}
	    }
	    return strResult;
	}
	catch (Exception ex)
	{
	    if (LogName != null)
	    {
		T9.Util.LogUtil.WriteLog("SendRequestUTF8-发生未知错误" + (Tag != null ? "[" + Tag + "]" : "") + ":\r\n" + ex.Message.ToString() + "\r\n报错详情:" + ex.StackTrace.ToString()
		   , LogName);
	    }
	    Status = "T9_9999";
	    return ex.Message;
	}
    }
    return strResult;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C#中调用HttpGet请求可以使用以下代码示例: ```csharp // 引用System.Net命名空间 using System.Net; public string HttpGet(string url) { // 创建WebRequest对象 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; // 设置请求头部 request.ContentType = "text/html, application/xhtml+xml, */*"; // 发送请求并获取响应 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream rs = response.GetResponseStream(); // 读取响应数据 StreamReader sr = new StreamReader(rs, Encoding.UTF8); string result = sr.ReadToEnd(); // 关闭StreamReader和Stream sr.Close(); rs.Close(); // 返回响应数据 return result; } ``` 以上代码是一个简单的C#函数,用于发起一个HttpGet请求,并返回响应数据。你可以将需要发送的URL作为参数传递给该函数,它将返回一个包含响应数据的字符串。这个函数使用了System.Net命名空间中的相关类和方法来发送和接收Http请求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [C# 实现HttpGet请求](https://blog.csdn.net/zq9955/article/details/112234498)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [C#调用Get请求](https://blog.csdn.net/qq_36263134/article/details/90444782)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [C# WebApi Get请求方式传递实体参数的方法示例](https://download.csdn.net/download/weixin_38592847/12749834)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可曾听闻丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值