string param = "<xml>" +"<ToUserName><![CDATA[toUser]]></ToUserName>" +"<FromUserName><![CDATA[fromUser]] ></FromUserName>" +"<CreateTime> 1348831860 ...
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;
}