string param = "<xml>"
+"<ToUserName><![CDATA[toUser]]></ToUserName>"
+"<FromUserName><![CDATA[fromUser]] ></FromUserName>"
+"<CreateTime> 1348831860 </CreateTime>"
+"<MsgType><![CDATA[text]] ></MsgType>"
+"<Content><![CDATA[this is a test]] ></Content>"
+"<MsgId> 1234567890123456 </MsgId>"
+"</xml> ";
//编码格式
Encoding encoding = Encoding.GetEncoding("UTF-8");
byte[] bs = encoding.GetBytes(param);
string text2 = string.Format("http://localhost:52827/api/Wx");
HttpWebRequest httpWebRequest = WebRequest.CreateHttp(text2);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = bs.Length;
using (Stream reqStream = httpWebRequest.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Flush();
reqStream.Close();
}
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
HttpWebResponse response = null;
try
{
using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), encoding))
{
while (streamReader.Peek() != -1)
{
string text = streamReader.ReadLine() + "\r\n";
}
}
}
catch (WebException ex)
{
if (ex.Response != null) //不正确的状态码
{
text = (HttpWebResponse)ex.Response;
}
}
catch (Exception ex)
{
//其他异常,连状态码都没能获取
throw ex;
}
/// <summary>
/// 调用WebApi获取数据
/// </summary>
/// <param name="msgModel">获取xxx对象的数据(WebApi中的方法名)</param>
/// <param name="param">需要传递的参数名字和值</param>
/// <returns>json数据</returns>
public static string GetMsg(string msgModel, string param)
{
if (string.IsNullOrWhiteSpace(msgModel))
{
return string.Empty;
}
string result = string.Empty;
string path = AppSetting.WEBAPI_ADDRESS + msgModel + param;
Uri resourceUri = new Uri(path);
HttpClientHandler handler = new HttpClientHandler();
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(300));
handler.AllowAutoRedirect = false;//是否应该跟随重定向相应
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;//使用客户端证书(应用的证书储存区自动选择最佳匹配的证书用于验证)
handler.UseProxy = false;//不适用代理
handler.UseDefaultCredentials = true;//是否使用默认用户验证
HttpClient httpclient = new HttpClient(handler);
httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = httpclient.GetAsync(resourceUri, cts.Token).Result;
if (response.EnsureSuccessStatusCode().IsSuccessStatusCode == true)
{
result = response.Content.ReadAsStringAsync().Result;
}
}
catch (TaskCanceledException ex)
{
// 因超时取消请求的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "GetMsg", ex.Message, ex.StackTrace);
}
catch (HttpRequestException ex)
{
// 处理其它可能异常的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "GetMsg", ex.Message, ex.StackTrace);
}
catch (Exception ex)
{
// 处理其它可能异常的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "GetMsg", ex.Message, ex.StackTrace);
}
return result;
}
/// <summary>
/// 调用WebApi发送post数据
/// </summary>
/// <param name="msgModel">发送xxx对象的数据(WebApi中的方法名)</param>
/// <param name="jsonData">需要发送的json数据</param>
/// <param name="paramName">需要传递的参数名字</param>
/// <returns>WebApi是否接收成功(success/fail/error)</returns>
public static string PostMsg(string msgModel, string jsonData, string paramName)
{
if (string.IsNullOrWhiteSpace(msgModel))// || string.IsNullOrWhiteSpace(jsonData)
{
return string.Empty;
}
string result = string.Empty;
string path = AppSetting.WEBAPI_ADDRESS + msgModel + paramName;
HttpClientHandler handler = new HttpClientHandler();
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(300));
handler.AllowAutoRedirect = false;//是否应该跟随重定向相应
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;//使用客户端证书(应用的证书储存区自动选择最佳匹配的证书用于验证)
handler.UseProxy = false;//不适用代理
handler.UseDefaultCredentials = true;//是否使用默认用户验证
HttpClient httpclient = new HttpClient(handler);
httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
Uri resourceUri = new Uri(path + jsonData);
//HttpResponseMessage response = httpclient.GetAsync(resourceUri, cts.Token).Result;
HttpResponseMessage response = httpclient.PostAsync(resourceUri, new StringContent(jsonData), cts.Token).Result;
if (response.EnsureSuccessStatusCode().IsSuccessStatusCode == true)
{
result = response.Content.ReadAsStringAsync().Result;
}
}
catch (TaskCanceledException ex)
{
// 因超时取消请求的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "PostMsg", ex.Message, ex.StackTrace);
}
catch (HttpRequestException ex)
{
// 处理其它可能异常的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "PostMsg", ex.Message, ex.StackTrace);
}
catch (Exception ex)
{
// 处理其它可能异常的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "PostMsg", ex.Message, ex.StackTrace);
}
return result;
}
public string PostXml(string url, string strPost)
{
string result = "";
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
//objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "text/xml";//提交xml
//objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}