using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using Newtonsoft.Json;
namespace Aitex.Core.MES
{
internal class HttpClient
{
///
/// 调用mes基础方法
///
///
///
///
public static string HttpPost(string url, IDictionary para)
{
try
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/x-www-form-urlencoded ";//根据服务端进行 切换
request.Timeout = 1000;
StringBuilder buffer = new StringBuilder();
int i = 0;
foreach (string key in para.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, para[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, para[key]);
}
i++;
}
byte[] buffer2 = encoding.GetBytes(buffer.ToString());
request.ContentLength = buffer2.Length;
request.GetRequestStream().Write(buffer2, 0, buffer2.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
catch (Exception ex)
{
return ex.Message;
}
}
public static string PostResponse(string url, string postData, out string statusCode)
{
string result = string.Empty;
//设置Http的正文
HttpContent httpContent = new StringContent(postData);
//设置Http的内容标头
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
//设置Http的内容标头的字符
httpContent.Headers.ContentType.CharSet = "utf-8";
using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
{
//异步Post
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
//输出Http响应状态码
statusCode = response.StatusCode.ToString();
//确保Http响应成功
if (response.IsSuccessStatusCode)
{
//异步读取json
result = response.Content.ReadAsStringAsync().Result;
}
}
return result;
}
public static string HttpGet(string url)
{
string strRet = string.Empty;
try
{
//url = "http://58.220.255.234:1005/api/mes/GetRecipeBySingleLot?strQuery=123";
//把URL初始化为新的WebRequest
HttpWebRequest Request = WebRequest.Create(url) as HttpWebRequest;
Request.Method = "GET";
//超时时间是2秒
Request.Timeout = 2000;
//初始化HTTP响应
HttpWebResponse Response = Request.GetResponse() as HttpWebResponse;
//获取HTTP响应流
Stream resStream = Response.GetResponseStream();
//读取数据流
using (StreamReader reader = new StreamReader(resStream))
{
strRet= reader.ReadToEnd();
return strRet;
}
////把数据流放到Char数组中
//Char[] read = new Char[256];
//int count = readStream.Read(read, 0, 256);
////开始读
//while (count > 0)
//{
// string str = new string(read, 0, count);
// //读出
// strRet += str;
// count = readStream.Read(read, 0, 256);
//}
//readStream.Close();
}
catch (Exception ex)
{
strRet = ex.Message;
}
return strRet;
}
}
}