Basf_FCL/FCL/BLL/Common/HttpHelper.cs

187 lines
6.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Common
{
public class HttpHelper
{
/// <summary>
/// Http Get Request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string HttpGetRequest(string url, string token ="")
{
string strGetResponse = string.Empty;
try
{
var getRequest = CreateHttpRequest(url,"GET", token);
var getResponse = getRequest.GetResponse() as HttpWebResponse;
strGetResponse = GetHttpResponse(getResponse, "GET");
}
catch (Exception ex)
{
strGetResponse = ex.Message;
}
return strGetResponse;
}
/// <summary>
/// Http Post Request
/// </summary>
/// <param name="url"></param>
/// <param name="postJsonData"></param>
/// <returns></returns>
public static string HttpPostRequest(string url, string postJsonData,string token)
{
BLL.ErrLogInfo.WriteLog("token=" + token);
string strPostReponse = string.Empty;
try
{
var postRequest = CreateHttpRequest(url, "POST",token, postJsonData);
var postResponse = postRequest.GetResponse() as HttpWebResponse;
strPostReponse = GetHttpResponse(postResponse, "POST");
BLL.ErrLogInfo.WriteLog("result=" + strPostReponse);
}
catch (Exception ex)
{
strPostReponse = ex.Message;
BLL.ErrLogInfo.WriteLog("error=" + ex.Message);
}
return strPostReponse;
}
public static string HttpPost(string Url, string jsonParas)
{
string strURL = Url;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/x-www-form-urlencoded";
//设置参数并进行URL编码
string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);
byte[] payload;
//将Json字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的ContentLength
request.ContentLength = payload.Length;
//发送请求,获得请求流
Stream writer;
try
{
writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
}
catch (Exception)
{
writer = null;
BLL.ErrLogInfo.WriteLog("连接服务器失败!");
}
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close();//关闭请求流
// String strValue = "";//strValue为http响应所返回的字符流
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream s = response.GetResponseStream();
// Stream postData = Request.InputStream;
StreamReader sRead = new StreamReader(s);
string postContent = sRead.ReadToEnd();
sRead.Close();
return postContent;//返回Json数据
}
private static HttpWebRequest CreateHttpRequest(string url, string requestType, string token, params object[] strJson)
{
HttpWebRequest request = null;
const string get = "GET";
const string post = "POST";
if (string.Equals(requestType, get, StringComparison.OrdinalIgnoreCase))
{
request = CreateGetHttpWebRequest(url,token);
}
if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
{
request = CreatePostHttpWebRequest(url, strJson[0].ToString(),token);
}
return request;
}
private static HttpWebRequest CreateGetHttpWebRequest(string url,string token)
{
var getRequest = HttpWebRequest.Create(url) as HttpWebRequest;
if (!string.IsNullOrEmpty(token))
{
getRequest.ContentType = "application/json";
getRequest.Headers.Add("token", token);
}
else
{
getRequest.ContentType = "text/html;charset=UTF-8";
}
getRequest.Method = "GET";
getRequest.Timeout = 5000;
getRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
return getRequest;
}
private static HttpWebRequest CreatePostHttpWebRequest(string url, string postData,string token)
{
var postRequest = HttpWebRequest.Create(url) as HttpWebRequest;
postRequest.KeepAlive = false;
postRequest.Method = "POST";
postRequest.ContentType = "application/x-www-form-urlencoded";
if (!string.IsNullOrEmpty(token))
{
postRequest.ContentType = "application/json";
postRequest.Headers.Add("token_app", token);
}
postRequest.ContentLength = postData.Length;
postRequest.AllowWriteStreamBuffering = false;
StreamWriter writer = new StreamWriter(postRequest.GetRequestStream(), Encoding.ASCII);
writer.Write(postData);
writer.Flush();
return postRequest;
}
private static string GetHttpResponse(HttpWebResponse response, string requestType)
{
var responseResult = "";
const string post = "POST";
string encoding = "UTF-8";
if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
{
encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8";
}
}
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)))
{
responseResult = reader.ReadToEnd();
}
return responseResult;
}
}
}