Http请求
Posted 322829
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Http请求相关的知识,希望对你有一定的参考价值。
调用:
Model u=new Model();
string aa = HttpClientHelper.RequestAPIPost("请求地址", u);
string bb = HttpClientHelper.RequestAPIGet("请求地址");
ListResult<Modelt> cc = HttpClientHelper.RequestAPIGet<ListResult<SMS_Class>>("请求地址");
using Common.Log;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
namespace Common.Http
/// <summary>
/// 类名:HttpClientHelper
/// 功能:网站模拟请求
/// 版本:4.0
/// 编写时间:2019/02/20
/// </summary>
public class HttpClientHelper
#region HTTP请求方法
/// <summary>
/// HTTP请求方法
/// </summary>
public enum MethodType
/// <summary>
/// 请求指定的页面信息,并返回实体主体。
/// </summary>
GET,
/// <summary>
/// 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST请求可能会导致新的资源的建立和/或已有资源的修改。
/// </summary>
POST,
/// <summary>
/// 类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头
/// </summary>
HEAD,
/// <summary>
/// 从客户端向服务器传送的数据取代指定的文档的内容。
/// </summary>
PUT,
/// <summary>
/// 请求服务器删除指定的页面。
/// </summary>
DELETE,
/// <summary>
/// HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。
/// </summary>
CONNECT,
/// <summary>
/// 允许客户端查看服务器的性能。
/// </summary>
OPTIONS,
/// <summary>
/// 回显服务器收到的请求,主要用于测试或诊断。
/// </summary>
TRACE
/// <summary>
/// Post请求
/// </summary>
/// <param name="requestUrl">地址</param>
/// <param name="data">请求参数</param>
/// <returns></returns>
public static string RequestAPIPost(string requestUrl, object data = null)
return RequestAPI(requestUrl, data, MethodType.POST);
/// <summary>
/// Get请求
/// </summary>
/// <param name="requestUrl">地址</param>
/// <param name="data">请求参数</param>
/// <returns></returns>
public static string RequestAPIGet(string requestUrl, object data = null)
return RequestAPI(requestUrl, data, MethodType.GET);
public static string RequestAPI(string requestUrl, object data = null, MethodType method = MethodType.POST)
string response = "";
try
if (method == MethodType.POST)
response = HttpRequest(requestUrl, ToJSON(data), Encoding.UTF8, MethodType.POST, "application/json");
else
response = HttpRequest(requestUrl, ToJSON(data), Encoding.UTF8, MethodType.GET, "application/json");
catch (Exception ex)
LogHelper.Info("请求url:" + requestUrl + "\\r\\n错误描述:" + ex.ToString());
return response;
/// <summary>
/// 返回实体类的Post请求
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="requestUrl">地址</param>
/// <param name="data">请求参数</param>
/// <returns></returns>
public static T RequestAPIPost<T>(string requestUrl, object data = null)
return RequestAPI<T>(requestUrl, data, MethodType.POST);
/// <summary>
/// 返回实体类的Get请求
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="requestUrl">地址</param>
/// <param name="data">请求参数</param>
/// <returns></returns>
public static T RequestAPIGet<T>(string requestUrl, object data = null)
return RequestAPI<T>(requestUrl, data, MethodType.GET);
public static T RequestAPI<T>(string requestUrl, object data = null, MethodType method = MethodType.POST)
string response = "";
try
if (method == MethodType.POST)
response = HttpRequest(requestUrl, ToJSON(data), Encoding.UTF8, MethodType.POST, "application/json");
else
response = HttpRequest(requestUrl, ToJSON(data), Encoding.UTF8, MethodType.GET, "application/json");
catch (Exception ex)
LogHelper.Info("请求url:" + requestUrl + "\\r\\n错误描述:" + ex.ToString());
return FromJSON<T>(response);
/// <summary>
/// 用户代理
/// </summary>
//private static readonly string UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (Khtml, like Gecko) Maxthon/4.1.2.4000 Chrome/26.0.1410.43 Safari/537.1";
/// <summary>
/// 模拟请求
/// </summary>
/// <param name="url">请求url</param>
/// <param name="methodType">请求类型</param>
/// <returns>返回结果</returns>
public static string HttpRequest(string url, MethodType type = MethodType.GET)
return HttpRequest(url, Encoding.UTF8, type);
/// <summary>
/// Post请求
/// </summary>
/// <param name="url">请求链接地址</param>
/// <param name="data">参数</param>
/// <returns>返回结果</returns>
public static string HttpRequest(string url, string data, MethodType type = MethodType.GET)
return HttpRequest(url, data, Encoding.UTF8, type);
/// <summary>
/// 模拟请求
/// </summary>
/// <param name="url">请求url</param>
/// <param name="coding">Encoding编码格式</param>
/// <param name="methodType">请求类型</param>
/// <returns>返回数据格式</returns>
public static string HttpRequest(string url, Encoding coding, MethodType type = MethodType.GET)
try
HttpWebResponse response = InitRequest(url, true, type.ToString(), "application/x-www-form-urlencoded", "").GetResponse() as HttpWebResponse;
return ReadResponseStream(response, coding);
catch (Exception ex)
throw ex;
/// <summary>
/// Post请求
/// </summary>
/// <param name="url">请求url</param>
/// <param name="data">post数据</param>
/// <param name="code">编码根式</param>
/// <param name="contentType">请求content格式</param>
/// <returns></returns>
public static string HttpRequest(string url, string data, Encoding code, MethodType type = MethodType.POST, string contentType = "application/x-www-form-urlencoded")
try
//发送请求并获取相应回应数据
HttpWebResponse response = InitRequest(url, true, type.ToString(), contentType, data).GetResponse() as HttpWebResponse;
return ReadResponseStream(response, code);
catch (Exception ex)
throw ex;
/// <summary>
/// 初始化请求对象
/// </summary>
/// <param name="url">请求url</param>
/// <param name="bAllowCookie">是否启用cookie</param>
/// <param name="methodType">请求类型</param>
/// <param name="contentType">请求参数类型</param>
/// <param name="data">请求数据</param>
/// <returns></returns>
private static HttpWebRequest InitRequest(string url, bool bAllowCookie, string methodType, string contentType, string data)
//请求对象配置
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
if (request != null)
if (bAllowCookie)
CookieContainer cookie = new CookieContainer();
request.CookieContainer = cookie;
request.AllowAutoRedirect = true;
request.Method = methodType;
//request.Timeout = 30000; //默认请求30s
//是否有请求数据
if (!string.IsNullOrEmpty(data))
request.ContentType = contentType;
byte[] buffer = Encoding.UTF8.GetBytes(data);
request.ContentLength = buffer.Length;
using (Stream stream = request.GetRequestStream())
stream.Write(buffer, 0, buffer.Length);
return request;
/// <summary>
/// 读取请求返回流信息
/// </summary>
/// <param name="response"></param>
/// <param name="coding"></param>
/// <returns></returns>
private static string ReadResponseStream(HttpWebResponse response, Encoding coding)
if (response != null)
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream, coding))
string result = reader.ReadToEnd();
return result;
return "";
#endregion
#region 文件上传与转换
/// <summary>
/// 根据链接地址模拟请求
/// 多媒体文件上传
/// </summary>
/// <param name="requestUrl">请求url</param>
/// <param name="filePath">文件路径(物理路径)</param>
/// <returns>返回结果</returns>
public static string HttpUploadFile(string requestUrl, string filePath)
if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(requestUrl))
return "";
//文件信息不存在
if (!File.Exists(filePath))
throw new ArgumentNullException("filePath文件不存在!");
using (WebClient client = new WebClient())
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
Uri url = new Uri(requestUrl);
byte[] buffer = client.UploadFile(url, filePath);
string result = Encoding.UTF8.GetString(buffer);
return result;
/// <summary>
/// 根据链接地址模拟请求
/// 获取到byte[] buffer 转换成文件
/// </summary>
/// <param name="url">请求url</param>
/// <returns>返回结果</returns>
public static byte[] HttpDownFile(string url)
using (WebClient requestClient = new WebClient())
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
Uri uri = new Uri(url);
byte[] buffer = requestClient.DownloadData(uri);
return buffer;
#endregion
#region Json转换
/// <summary>
/// 获取Json对象属性值
/// </summary>
/// <param name="json">json对象数据源</param>
/// <param name="pKey">属性名称Key</param>
/// <returns></returns>
public static string GetValueByJson(string json, string pKey)
if (json == null || json.Trim().Length == 0)
return "";
javascriptSerializer js = new JavaScriptSerializer();
try
object obj = js.Deserialize<object>(json);
Dictionary<string, object> dTemp = (Dictionary<string, object>)obj;
if (dTemp.ContainsKey(pKey))
return dTemp[pKey].ToString();
return string.Empty;
catch (Exception)
return string.Empty;
/// <summary>
/// 内存对象转换为json字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJSON(object obj)
StringBuilder sb = new StringBuilder();
JavaScriptSerializer json = new JavaScriptSerializer();
if (obj == null)
return sb.ToString();
json.Serialize(obj, sb);
return sb.ToString();
/// <summary>
/// Json字符串转内存对象
/// </summary>
/// <param name="jsonString"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static T FromJSON<T>(string jsonString)
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Deserialize<T>(jsonString);
#endregion
以上是关于Http请求的主要内容,如果未能解决你的问题,请参考以下文章