/// <summary>
/// post调用
/// </summary>
/// <param name="url"></param>
/// <param name="body"></param>
/// <param name="header"></param>
/// <returns></returns>
public static string AskDataPost(string url, string body, string header, string methtype, string ContentType, string headertype)
{
string result = "";
try
{
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (!string.IsNullOrEmpty(header))
{
//request.Headers.Set("api-key", header);
//request.Headers.Set("Authorization", header);
if (!string.IsNullOrEmpty(headertype))
{
request.Headers.Set(headertype, header);
}
}
request.Method = methtype;
request.Accept = "text/html, application/xhtml+xml, */*";
//request.ContentType = "application/json";
request.ContentType = ContentType;
//request.CookieContainer = new CookieContainer();
//request.Timeout = 10000;
request.UserAgent = ".NET Framework Test Client";
request.Credentials = CredentialCache.DefaultCredentials;byte[] buffer = encoding.GetBytes(body);
request.ContentLength = buffer.Length;request.MaximumAutomaticRedirections = 1;
request.AllowAutoRedirect = true;//request.GetRequestStream().Write(buffer, 0, buffer.Length);
// 发送请求
Stream newStream = request.GetRequestStream();
newStream.Write(buffer, 0, buffer.Length);
newStream.Close();HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
result = reader.ReadToEnd();
reader.Close();
response.Close();
}}
catch (System.Net.WebException ex)
{
try
{
var mResponse = ex.Response as HttpWebResponse;
var responseStream = mResponse.GetResponseStream();
if (responseStream != null)
{
var streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
//获取返回的信息
result = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
}
}
catch (Exception ex1)
{
}//result = "获取数据失败,请重试!" + url + ex.ToString() + " 返回数据" + result;
}
return result;
}
/// <summary>
/// Get调用
/// </summary>
/// <param name="url"></param>
/// <param name="header"></param>
/// <returns></returns>
public static string AskDataGet(string url, string header, string ContentType)
{
//创建restful的请求
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
if (!string.IsNullOrEmpty(header))
{
request.Headers.Set("api-key", header);
}
request.Method = "GET";
//request.ContentType = "application/json";
request.ContentType = ContentType;//接收来自restful的回复
string json = string.Empty; //返回的类型是json格式字符串,声明一个来接收
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//以流的形式读取,返回的就是字符串的json格式
StreamReader reader = new StreamReader(response.GetResponseStream());
json = reader.ReadToEnd();
}
return json;
}