1. 程式人生 > >C#使用RestSharp實現post傳送

C#使用RestSharp實現post傳送

最近做C#上傳,不過在使用HttpWebRequest時遇到了奇怪的超時問題,一時無法解決。

於是找找其他辦法,發現了RestSharp,快捷,好用,用法如下:

using RestSharp;

string url = "http://...";
string content = "..."; //要傳送的內容
string contentType = "application/json"; //Content-Type

try
{
    var client = new RestClient(url);
    var request = new RestRequest(Method.POST);
    request.Timeout = 10000;
    //request.AddHeader("Cache-Control", "no-cache");          
    request.AddParameter(contentType, content, ParameterType.RequestBody);

    IRestResponse response = client.Execute(request);
    return response.Content; //返回的結果
}
catch (Exception ex)
{
     return "連線伺服器出錯:\r\n" + ex.Message;
}