using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Utils.Log4Net;
namespace Utils
{
public class HttpHelper
{
public static string httpGet(string strURL)
{
try
{
System.Net.HttpWebRequest request;
// 创建一个HTTP请求
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
//request.Method="get";
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
return responseText;
}
catch (Exception ex)
{
return "";
}
}
public static string httpZipGet(string strURL)
{
try
{
System.Net.HttpWebRequest request;
// 创建一个HTTP请求
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
//request.Method="get";
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
//myreader.
string responseText = myreader.ReadToEnd();
myreader.Close();
return responseText;
}
catch (Exception ex)
{
return "";
}
}
public static string httpPost(string strURL,Dictionary<string,string> dParm)
{
try
{
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
request.Timeout = 1000 * 60;
// 内容类型
request.ContentType = "application/x-www-form-urlencoded";
string paraUrlCoded = "";
if (dParm != null && dParm.Count > 0)
{
foreach (string key in dParm.Keys)
{
if (paraUrlCoded.Length > 0)
{
paraUrlCoded += "&"+System.Web.HttpUtility.UrlEncode(key);
}
else
{
paraUrlCoded +=System.Web.HttpUtility.UrlEncode(key);
}
paraUrlCoded += "="+System.Web.HttpUtility.UrlEncode(dParm[key]);
}
}
// 参数经过URL编码
//string paraUrlCoded = System.Web.HttpUtility.UrlEncode("keyword");
//paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode("多月");
byte[] payload;
//将URL编码后的字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的 ContentLength
request.ContentLength = payload.Length;
//获得请 求流
System.IO.Stream writer = request.GetRequestStream();
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
// 关闭请求流
writer.Close();
System.Net.HttpWebResponse response;
// 获得响应流
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
return responseText;
}
catch (Exception ex)
{
LogHelper.Info(strURL + " "+ex.Message);
return "";
}
}
public static string PostJson(string Url, string jsonParas)
{
try
{
string strURL = Url;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/json";
//设置参数,并进行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;
Console.Write("连接服务器失败!");
}
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close();//关闭请求流
String strValue = "";//strValue为http响应所返回的字符流
HttpWebResponse response;
//获得响应流
response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
Stream postData = response.GetResponseStream(); ;
StreamReader sRead = new StreamReader(s);
string postContent = sRead.ReadToEnd();
sRead.Close();
return postContent;//返回Json数据
}catch (Exception e)
{
return "";
}
}
public static void httpMultipartPost(string url,MultipartFormDataContent requestContent)
{
try
{
//byte[] ImageData = new byte[100];
//var imageContent = new ByteArrayContent(ImageData);
//imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
//string filename = Guid.NewGuid().ToString().Replace("-","");
//requestContent.Add(imageContent, filename, filename+".jpg");
//var request=new SignData();
//request.photoName = "tmp_name";
//request.signId ="";
//request.signMode="1";
//request.signTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
//List<SignData> lst = new List<SignData>();
//lst.Add(request);
//var signData = new StringContent(JsonConvert.SerializeObject(lst));
//signData.Headers.Add("Content-Disposition", "form-data; name=\"signData\"");
//requestContent.Add(signData, "signData");
//var terminalId = new StringContent("");
//terminalId.Headers.Add("Content-Disposition", "form-data; name=\"terminalId\"");
//requestContent.Add(terminalId, "terminalId");
var client = new HttpClient();
Task<HttpResponseMessage> message = client.PostAsync(url, requestContent);
var input = message.Result.Content.ReadAsStringAsync();
}catch(Exception e)
{
}
}
public static string PostJsonWithTxtType(string Url, string jsonParas)
{
try
{
string strURL = Url;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/x-www-form-urlencoded";
// request.ContentType = "application/json";
//设置参数,并进行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;
Console.Write("连接服务器失败!");
}
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close();//关闭请求流
String strValue = "";//strValue为http响应所返回的字符流
HttpWebResponse response;
//获得响应流
response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
Stream postData = response.GetResponseStream(); ;
StreamReader sRead = new StreamReader(s);
string postContent = sRead.ReadToEnd();
sRead.Close();
return postContent;//返回Json数据
}
catch (Exception e)
{
LogHelper.Info(e.Message);
return "";
}
}
public static string httpPostFormData(string url, Dictionary<string, string> dic)
{
try
{
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
webReq.Method = "POST";
//webReq.Headers.Add("token", System.Configuration.ConfigurationSettings.AppSettings["erp_token"].ToString());
webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
webReq.KeepAlive = true;
webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
string boundary = "----" + DateTime.Now.Ticks.ToString("x");
string formdataTemplate = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
string dataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
webReq.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
Stream requestStream = webReq.GetRequestStream();
//尾
var footer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
if (dic != null && dic.Keys.Count > 0)
{
foreach (var kk in dic)
{
string key = kk.Key;
string val = kk.Value;
var dataByte = Encoding.ASCII.GetBytes(string.Format(dataTemplate, key, val));
requestStream.Write(dataByte, 0, dataByte.Length);//写入 参数1
}
}
requestStream.Write(footer, 0, footer.Length);//写入 尾
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string Info = sr.ReadToEnd();
sr.Close();
response.Close();
return Info;
}
catch(Exception ex)
{
LogHelper.Err(ex.Message);
return "";
}
}
}
}