using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using System.Collections;
using System.Web;
using System.Reflection;
using Newtonsoft.Json.Linq;
namespace SBP2023.Application.Tools
{
/// <summary>
/// Web服务工具类
/// </summary>
public static class WebService
{
#region 发起请求
/// <summary>
/// 发送POST请求
/// </summary>
/// <param name="weburl">请求的url</param>
/// <param name="data">传递的数据</param>
/// <param name="encode">编码格式</param>
/// <param name="Mothed">请求方式</param>
/// <returns></returns>
public static string PushToWeb(string weburl, string data, Encoding encode, string Mothed)
{
byte[] byteArray = encode.GetBytes(data);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(weburl));
webRequest.Method = Mothed;
if (Mothed == "POST")
webRequest.ContentType = "application/x-www-form-urlencoded";
else
return HttpGet(weburl, data);
webRequest.ContentLength = byteArray.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
//接收返回信息:
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader aspx = new StreamReader(response.GetResponseStream(), encode);
string result = aspx.ReadToEnd();
return result;
}
/// <summary>
/// 发起Get请求
/// </summary>
/// <param name="Url"></param>
/// <param name="postDataStr">参数字符串</param>
/// <returns></returns>
public static string HttpGet(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
#endregion
}
}
发起web请求
最新推荐文章于 2024-09-10 14:20:13 发布