/// <summary>
///
/// </summary>
/// <param name="requestURI">请求地址</param>
/// <param name="requestMethod">请求方式</param>
/// <param name="json">json入参</param>
/// <returns></returns>
public static string SendHttpRequest(string requestURI, string requestMethod, string json = "")
{
string ReqResult = string.Empty;
try
{
//json格式请求数据
string requestData = json;
//拼接URL
string serviceUrl = requestURI;//string.Format("{0}/{1}", requestURI, requestMethod);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
//post请求
myRequest.Method = requestMethod;
//utf-8编码
byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(requestData);
myRequest.ContentLength = buf.Length;
myRequest.Timeout = 60000;
//指定为json否则会出错
myRequest.ContentType = "application/json";
myRequest.MaximumAutomaticRedirections = 1;
myRequest.AllowAutoRedirect = true;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(buf, 0, buf.Length);
newStream.Close();
//获得接口返回值
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
ReqResult = reader.ReadToEnd();
reader.Close();
myResponse.Close();
return ReqResult;
}
catch (Exception ex)
{
return ReqResult = ex.Message.ToString();
}
}
以上则是基本HTTP请求---Json入参格式
HTTP基本请求---zip文件入参(hander 账号密码加密处理)
/// <summary>
/// Post-上传文件 上传请求zip格式文件
/// </summary>
/// <param name="url">上传请求地址</param>
/// <param name="postData">文件地址</param>
/// <returns></returns>
public static string PostResponse(string url, string postData, out string statusCode)
{
string result = string.Empty;
HttpResponseMessage response2 = new HttpResponseMessage();
//设置Http的正文
HttpContent httpContent = new StringContent(postData);
//根据form表单 上传格式设置对应参数
var content = new MultipartFormDataContent();
if (postData.Contains("QyTest"))
{
content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(postData)), "dataFile", "QyTest.zip");
}
else
{
content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(postData)), "dataFile", "RyTest02.zip");
}
string str = "******";//hander 登录账号
content.Add(new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(str)), "unitCode");
str = "********";//hander 登录密码
content.Add(new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(str)), "password");
//设置Http的内容标头
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
//设置Http的内容标头的字符
httpContent.Headers.ContentType.CharSet = "utf-8";
using (HttpClient httpClient = new HttpClient())
{
string value = "unitCode=00000:password=000000";//请求头 账号密码,与上方hander一致,根据业务需求来决定编写在哪
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.Default.GetBytes(value)));//转换basic 加密拼接
httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
//异步发送Post请求
try
{
response2 = httpClient.PostAsync(url, content).Result;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//Http响应状态码
statusCode = response2.StatusCode.ToString();
//确保Http响应成功
if (response2.IsSuccessStatusCode)
{
//异步读取返回信息
result = response2.Content.ReadAsStringAsync().Result;
}
}
return result;
}
POST请求,请求数据格式: x-www-form-urlencoded
/// <summary>
///
/// </summary>
/// <param name="requestURI">请求地址</param>
/// <param name="requestMethod">post/get</param>
/// <param name="json">请求数据</param>
/// <returns></returns>
public static string SendHttpRequest(string requestURI, string requestMethod, string json = "")
{
//json格式请求数据
string requestData = json;
//拼接URL
string serviceUrl = requestURI;//string.Format("{0}/{1}", requestURI, requestMethod);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
//post请求
myRequest.Method = requestMethod;
//utf-8编码
byte[] buf = System.Text.Encoding.Default.GetBytes(requestData);
myRequest.ContentLength = buf.Length;
myRequest.Timeout = 50000;
//指定为json否则会出错
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.MaximumAutomaticRedirections = 1;
myRequest.AllowAutoRedirect = true;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(buf, 0, buf.Length);
newStream.Close();
//获得接口返回值
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string ReqResult = reader.ReadToEnd();
reader.Close();
myResponse.Close();
return ReqResult;
}
x-www-form-urlencoded 及是 Url数据格式,以下本人封装了一个Model转Url数据方法
/// <summary>
/// x-www-form-urlencoded请求参数拼接
/// </summary>
/// <param name="source">model</param>
/// <returns>Url数据</returns>
public static string ToUrlPaeameter(object source)
{
var buff = new StringBuilder(string.Empty);
if (source == null) throw new ArgumentNullException("source", "入参为空");
foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(source))
{
object value = property.GetValue(source);
if (value != null)
{
buff.Append(WebUtility.UrlEncode(property.Name) + "=" + WebUtility.UrlEncode(value + "") + "&");
}
}
return buff.ToString().Trim('&');
}