1.傳遞匿名對象JSON格式 2.multipart/form-data上傳文件 根據Restsharp源碼可以發現如果使用了AddFile了會自動添加multipart/form-data參數 3.直接傳遞不帶參數的RequestBody:有的時候介面並不包含參數名而是直接以body流的方式傳輸的 ...
1.傳遞匿名對象JSON格式
public string Pay(string apisecret, string apikey, string token) { try { string url = "https://******//test"; var client = new RestClient(url); var request = new RestRequest(Method.POST); var tran = new { merchant_ref = "Astonishing-Sale", transaction_type = "purchase" }; //生成隨機數 RandomNumberGenerator rng = RNGCryptoServiceProvider.Create(); byte[] random = new Byte[8]; rng.GetBytes(random); string NONCE = Math.Abs(BitConverter.ToInt64(random, 0)).ToString(); //生成時間戳 string TIMESTAMP = ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds).ToString(); //獲取JSON字元內容 string paybody = string.Empty; if (tran.transaction_type != null) { paybody = SimpleJson.SerializeObject(tran); } string auth = GetAuth(apisecret, apikey, token, paybody, NONCE, TIMESTAMP); request.AddHeader("Content-Type", "application/json"); request.AddHeader("apikey", apikey); request.AddHeader("token", token); request.AddHeader("Authorization", auth); request.AddHeader("nonce", NONCE); request.AddHeader("timestamp", TIMESTAMP); request.AddJsonBody(tran);//自動轉換為JSON IRestResponse response = client.Execute(request); var content = response.Content; return content; } catch (Exception e) {return string.Empty; } }
2.multipart/form-data上傳文件
根據Restsharp源碼可以發現如果使用了AddFile了會自動添加multipart/form-data參數
string server = "http://*****//Upload"; string picurl = "C:\\Users\\Administrator\\Desktop\\555.png"; string testparams = "testpicupload"; RestClient restClient = new RestClient(server); //restClient.Encoding = Encoding.GetEncoding("GBK");//設置編碼格式 RestRequest restRequest = new RestRequest("/images"); restRequest.RequestFormat = DataFormat.Json; restRequest.Method = Method.POST; //restRequest.AddHeader("Authorization", "Authorization");//當需要設置認證Token等情況時使用預設不需要 //restRequest.AddHeader("Content-Type", "multipart/form-data");//如果使用了AddFile會自動添加否則請手動設置 restRequest.AddParameter("test", testparams); // restRequest.AddFile("pic", picurl);//壓縮格式 restRequest.AddFile("pic", picurl, contentType: "application/x-img"); //非壓縮格式 如果此處不設置為contentType 則預設壓縮格式 var response = restClient.Execute(restRequest); var info= response.Content;
3.直接傳遞不帶參數的RequestBody:有的時候介面並不包含參數名而是直接以body流的方式傳輸的這時候使用上面添加參數的方式就無效了,如果發送呢,RestSharp里保留了AddBody和 ParameterType.RequestBody來實現
request.AddParameter("text/xml", body, ParameterType.RequestBody); req.AddParameter("application/json", body, ParameterType.RequestBody);
根據AddBody源碼發現實際轉換最終使用的都是 AddParameter(contentType, serialized, ParameterType.RequestBody) 這個方法
public IRestRequest AddBody(object obj, string xmlNamespace) { string serialized; string contentType; switch (this.RequestFormat) { case DataFormat.Json: serialized = this.JsonSerializer.Serialize(obj); contentType = this.JsonSerializer.ContentType; break; case DataFormat.Xml: this.XmlSerializer.Namespace = xmlNamespace; serialized = this.XmlSerializer.Serialize(obj); contentType = this.XmlSerializer.ContentType; break; default: serialized = ""; contentType = ""; break; } // passing the content type as the parameter name because there can only be // one parameter with ParameterType.RequestBody so name isn't used otherwise // it's a hack, but it works :) return this.AddParameter(contentType, serialized, ParameterType.RequestBody); }
/// <summary> /// Adds a parameter to the request. There are four types of parameters: /// - GetOrPost: Either a QueryString value or encoded form value based on method /// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection /// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} /// - RequestBody: Used by AddBody() (not recommended to use directly) /// </summary> /// <param name="name">Name of the parameter</param> /// <param name="value">Value of the parameter</param> /// <param name="type">The type of parameter to add</param> /// <returns>This request</returns> public IRestRequest AddParameter(string name, object value, ParameterType type) { return this.AddParameter(new Parameter { Name = name, Value = value, Type = type }); }
4..二進位數據:(如下方式發送的格式和直接使用二進位寫入是相同的)
string server = "http://******/Upload";
RestClient restClient = new RestClient(server);
restClient.Encoding = Encoding.GetEncoding("GBK");//設置編碼格式
RestRequest restRequest = new RestRequest(Method.POST);
restRequest.Method = Method.POST;
var bb = new byte[] { 0x30, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x12, 0x40, 0x42 };
restRequest.AddParameter("application/pdf", bb, ParameterType.RequestBody);
var response = restClient.Execute(restRequest);
string s = response.Content;
測試Demo:
[TestMethod] public void TestRestsharpBinaryBody() { string server = "http://******/Upload"; RestClient restClient = new RestClient(server); restClient.Encoding = Encoding.GetEncoding("GBK");//設置編碼格式 RestRequest request = new RestRequest(Method.POST); request.Method = Method.POST; //===========二進位===測試通過================= //var bb = new byte[] { 0x30, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,0x40, 0x42 }; //request.AddParameter("application/pdf", bb, ParameterType.RequestBody); //==============XML字元串=====測試通過============== /** * 發送內容 * <root></root> * */ string x = "<root></root>";//XML字元串 request.AddParameter("text/xml", x, ParameterType.RequestBody); //=============Json轉換================== /** * 發送內容 * {"id":1,"name":"zhangsan"} * */ //var x = new { id = 1, name = "zhangsan" }; //request.AddJsonBody(x); //============object轉XML============== /** * 發送內容 * <Dummy> <A>Some string</A> <B>Some string</B> </Dummy> * */ //request.AddXmlBody(new Dummy());//對象轉XML 非匿名對象可以 匿名對象失敗 /*** * 發送內容 <Dummy xmlns="Root"> <A>Some string</A> <B>Some string</B> </Dummy> * */ request.AddXmlBody(new Dummy(),"Root");//對象轉XML 非匿名對象可以 匿名對象失敗 Root為命名空間 var response = restClient.Execute(request); string s = response.Content; Assert.IsNotNull(response.Content); }
public class Dummy { public string A { get; set; } public string B { get; set; } public Dummy() { A = "Some string"; B = "Some string"; } }