C#Http請求

来源:http://www.cnblogs.com/XiaoPengy/archive/2017/10/18/7688236.html
-Advertisement-
Play Games

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;
}


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Expect是在Tcl基礎上創建起來的,它還提供了一些Tcl所沒有的命令,它可以用來做一些linux下無法做到交互的一些命令操作,在遠程管 理方面發揮很大的作用。 spawn命令激活一個Unix程式來進行互動式的運行。 send命令向進程發送字元串。 expect 命令等待進程的某些字元串。 exp ...
  • 本文目錄:1. nginx簡介2. nginx處理請求的過程簡單說明3. nginx命令4. nginx模塊及http功能速覽5. nginx配置文件簡單說明 5.1 main和events段 5.2 http段 5.2.1 配置文件概覽 5.2.2 root指令和alias指令 5.2.3 loc ...
  • 1》概述 作為一名運維人員,保證數據的安全是根本職責,所以在維護系統的時候,要慎重和細心,但是有時也難免發生出現數據被誤刪除的情況,這個時候該如何 快速、有效地恢複數據呢? 1>如何使用rm –rf命令 在Linux系統下,通過 rm –rf 可以將任何數據直接從硬碟刪除,並且沒有任何提示,同時Li ...
  • ...
  • vs2015卸載後註冊表還會存在vs2015的信息,下次安裝的時候會讀註冊表裡面記錄的路徑,不能自己選擇路徑。 解決方法: 1.在vs安裝文件的路徑打開命令,shift+滑鼠右鍵 2.輸入命令:cn_visual_studio_enterprise.exe/U /Force 3.經過第2步,程式會把 ...
  • 做慣了後臺的沐雨一向覺得數據列表是一個系統裡面最重要的東西 所以熟悉ext也就從表格開始入手了 想看官方代碼的同學進這裡 官方預設表格教程 或是直接看我的也行,直接拷貝過來的 另外官方文檔沒有中文版的讓我這個二級都沒過的學渣倍感壓力啊 1. Views部分代碼 官方文檔一直沒看到下圖Layout的代 ...
  • MemLoadDll.h MemLoadDll.cpp ...
  • 轉自:http://blog.csdn.net/jxufewbt/article/details/1769312 應用程式之間的數據交換(互相通訊)一直是困擾廣大程式員的難題,儘管已經出現了各式各樣的解決方案,但迄今為止沒有哪一種方案是完美無缺的。因此,只有學習並瞭解了它們的優缺點後,才能在特定的情 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...