本文整理汇总了C#中RestRequest类的典型用法代码示例。如果您正苦于以下问题:C# RestRequest类的具体用法?C# RestRequest怎么用?C# RestRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
RestRequest类属于命名空间,在下文中一共展示了RestRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MultipartFormData_WithParameterAndFile
public void MultipartFormData_WithParameterAndFile()
{
const string baseUrl = "http://localhost:8888/";
using (SimpleServer.Create(baseUrl, EchoHandler))
{
RestClient client = new RestClient(baseUrl);
RestRequest request = new RestRequest("/", Method.POST)
{
AlwaysMultipartFormData = true
};
DirectoryInfo directoryInfo = Directory.GetParent(Directory.GetCurrentDirectory())
.Parent;
if (directoryInfo != null)
{
string path = Path.Combine(directoryInfo.FullName, "Assets\\TestFile.txt");
request.AddFile("fileName", path);
}
request.AddParameter("controlName", "test", "application/json", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Assert.AreEqual(this.expectedFileAndBodyRequestContent, response.Content);
}
}
示例2: GetSession
public RestSession GetSession(
RestRequest request,
out bool newSession)
{
Cookie sessionCookie = request.Cookies[SESSION_KEY];
string sessionId = "";
RestSession session = null;
if (sessionCookie != null)
{
sessionId = sessionCookie.Value;
newSession = false;
}
else
{
sessionId = GenerateNewSessionKey();
newSession = true;
}
if (!m_sessions.TryGetValue(sessionId, out session))
{
// TODO: What about expiring old sessions?
session = new RestSession(sessionId);
m_sessions.Add(sessionId, session);
}
return session;
}
示例3: Cannot_Set_Invalid_Host_Header
public void Cannot_Set_Invalid_Host_Header(string value)
{
RestRequest request = new RestRequest();
ArgumentException exception = Assert.Throws<ArgumentException>(() => request.AddHeader("Host", value));
Assert.AreEqual("value", exception.ParamName);
}
示例4: MultipleRequestsFromSameClientShouldNotFail
public async Task MultipleRequestsFromSameClientShouldNotFail()
{
// Setup
var client = new RestClient { BaseUrl = BaseAddress };
var request = new RestRequest("api/books");
List<Book> response;
// Execute
using (WebApp.Start<WebApiStartup>(BaseAddress))
{
response = await client.ExecuteAsync<List<Book>>(request);
}
// Validate
response.Should().NotBeNull();
response.Count().Should().Be(5);
var request2 = new RestRequest("api/books");
List<Book> response2;
// Execute
using (WebApp.Start<WebApiStartup>(BaseAddress))
{
response2 = await client.ExecuteAsync<List<Book>>(request2);
}
// Validate
response2.Should().NotBeNull();
response2.Count().Should().Be(5);
}
示例5: Can_Handle_Uncompressed_Content
public void Can_Handle_Uncompressed_Content()
{
var client = new RestClient(BaseUrl);
var request = new RestRequest("Compression/None");
var response = client.Execute(request);
Assert.Equal("This content is uncompressed!", response.Content);
}
示例6: AddApplicationAsyncInternal
private async Task<Application> AddApplicationAsyncInternal(string friendlyName, ApplicationOptions options)
{
var request = new RestRequest();
request.Method = Method.POST;
request.Resource = "Accounts/{AccountSid}/Applications.json";
Require.Argument("FriendlyName", friendlyName);
Validate.IsValidLength(friendlyName, 64);
request.AddParameter("FriendlyName", friendlyName);
// some check for null. in those cases an empty string is a valid value (to remove a URL assignment)
if (options != null)
{
if (options.VoiceUrl != null) request.AddParameter("VoiceUrl", options.VoiceUrl);
if (options.VoiceMethod.HasValue()) request.AddParameter("VoiceMethod", options.VoiceMethod.ToString());
if (options.VoiceFallbackUrl != null) request.AddParameter("VoiceFallbackUrl", options.VoiceFallbackUrl);
if (options.VoiceFallbackMethod.HasValue()) request.AddParameter("VoiceFallbackMethod", options.VoiceFallbackMethod.ToString());
if (options.VoiceCallerIdLookup.HasValue) request.AddParameter("VoiceCallerIdLookup", options.VoiceCallerIdLookup.Value);
if (options.StatusCallback.HasValue()) request.AddParameter("StatusCallback", options.StatusCallback);
if (options.StatusCallbackMethod.HasValue()) request.AddParameter("StatusCallbackMethod", options.StatusCallbackMethod.ToString());
if (options.SmsUrl != null) request.AddParameter("SmsUrl", options.SmsUrl);
if (options.SmsMethod.HasValue()) request.AddParameter("SmsMethod", options.SmsMethod.ToString());
if (options.SmsFallbackUrl != null) request.AddParameter("SmsFallbackUrl", options.SmsFallbackUrl);
if (options.SmsFallbackMethod.HasValue()) request.AddParameter("SmsFallbackMethod", options.SmsFallbackMethod.ToString());
}
var result = await ExecuteAsync(request, typeof(Application));
return (Application)result;
}
示例7: Handles_Server_Timeout_Error_Async
public void Handles_Server_Timeout_Error_Async()
{
const string baseUrl = "http://localhost:8888/";
var resetEvent = new ManualResetEvent(false);
using (SimpleServer.Create(baseUrl, TimeoutHandler))
{
var client = new RestClient(baseUrl);
var request = new RestRequest("404") { Timeout = 500 };
IRestResponse response = null;
client.ExecuteAsync(request, responseCb =>
{
response = responseCb;
resetEvent.Set();
});
resetEvent.WaitOne();
Assert.NotNull(response);
Assert.Equal(response.ResponseStatus, ResponseStatus.TimedOut);
Assert.NotNull(response.ErrorException);
Assert.IsAssignableFrom(typeof(WebException), response.ErrorException);
Assert.Equal(response.ErrorException.Message, "The request timed-out.");
}
}
开发者ID:mgulubov,项目名称:RestSharpHighQualityCodeTeamProject,代码行数:26,代码来源:NonProtocolExceptionHandlingTests.cs
示例8: Task_Handles_Non_Existent_Domain
public void Task_Handles_Non_Existent_Domain()
{
var client = new RestClient("http://192.168.1.200:8001");
var request = new RestRequest("/")
{
RequestFormat = DataFormat.Json,
Method = Method.GET
};
AggregateException agg = Assert.Throws<AggregateException>(
delegate
{
var response = client.ExecuteTaskAsync<StupidClass>(request);
response.Wait();
});
Assert.IsType(typeof(WebException), agg.InnerException);
Assert.Equal("Unable to connect to the remote server", agg.InnerException.Message);
//var client = new RestClient("http://nonexistantdomainimguessing.org");
//var request = new RestRequest("foo");
//var response = client.ExecuteTaskAsync(request);
//Assert.Equal(ResponseStatus.Error, response.Result.ResponseStatus);
}
示例9: Execute
/// <summary>
/// Retrieves a new token from Webtrends auth service
/// </summary>
public string Execute()
{
var builder = new JWTBuilder();
var header = new JWTHeader
{
Type = "JWT",
Algorithm = "HS256"
};
var claimSet = new JWTClaimSet
{
Issuer = clientId,
Principal = clientId,
Audience = audience,
Expiration = DateTime.Now.ToUniversalTime().AddSeconds(30),
Scope = scope
};
string assertion = builder.BuildAssertion(header, claimSet, clientSecret);
var client = new RestClient(authUrl);
var request = new RestRequest("token/", Method.POST);
request.AddParameter("client_id", clientId);
request.AddParameter("client_assertion", assertion);
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
var response = client.Execute(request).Content;
return (string)JObject.Parse(response)["access_token"];
}
示例10: InvokeAsyncMethodWithGetRequest
public void InvokeAsyncMethodWithGetRequest()
{
//Arrange
RestInvoker target = new RestInvoker();
StubModule.HaltProcessing = TimeSpan.FromSeconds(0);
StubModule.GetPerson = false;
StubModule.TestHarness = new List<Person> { new Person { Id = 1, Email = "[email protected]" } };
RestRequest request = new RestRequest(HttpMethod.GET, new RestUri(_MyUri, "/Person/{id}").SetParameter("id", "1"));
//Act
target.InvokeAsync(request).ContinueWith(task =>
{
using (var actual = task.Result)
{
//Assert
Assert.True(StubModule.GetPerson);
Assert.True(actual.IsSuccessStatusCode);
Assert.NotNull(actual);
string content = actual.Body.ReadAsString();
Assert.Equal("{\"Id\":1,\"UID\":\"00000000-0000-0000-0000-000000000000\",\"Email\":\"[email protected]\",\"NoOfSiblings\":0,\"DOB\":\"\\/Date(-59011459200000)\\/\",\"IsActive\":false,\"Salary\":0}", content);
}
}).Wait();
}
示例11: Handles_Non_Existent_Domain
public void Handles_Non_Existent_Domain()
{
var client = new RestClient("http://nonexistantdomainimguessing.org");
var request = new RestRequest("foo");
var response = client.Execute(request);
Assert.Equal(ResponseStatus.Error, response.ResponseStatus);
}
示例12: Can_Handle_Exception_Thrown_By_OnBeforeDeserialization_Handler
public void Can_Handle_Exception_Thrown_By_OnBeforeDeserialization_Handler()
{
const string baseUrl = "http://localhost:8080/";
const string ExceptionMessage = "Thrown from OnBeforeDeserialization";
using (SimpleServer.Create(baseUrl, Handlers.Generic<ResponseHandler>()))
{
var client = new RestClient(baseUrl);
var request = new RestRequest("success");
request.OnBeforeDeserialization += response =>
{
throw new Exception(ExceptionMessage);
};
var task = client.ExecuteTaskAsync<Response>(request);
try
{
// In the broken version of the code, an exception thrown in OnBeforeDeserialization causes the task to
// never complete. In order to test that condition, we'll wait for 5 seconds for the task to complete.
// Since we're connecting to a local server, if the task hasn't completed in 5 seconds, it's safe to assume
// that it will never complete.
Assert.True(task.Wait(TimeSpan.FromSeconds(5)), "It looks like the async task is stuck and is never going to complete.");
}
catch (AggregateException e)
{
Assert.Equal(1, e.InnerExceptions.Count);
Assert.Equal(ExceptionMessage, e.InnerExceptions.First().Message);
return;
}
Assert.True(false, "The exception thrown from OnBeforeDeserialization should have bubbled up.");
}
}
示例13: TestMultipleRequests
public async Task TestMultipleRequests(Type factoryType)
{
using (var client = new RestClient("http://httpbin.org/")
{
HttpClientFactory = CreateClientFactory(factoryType, false),
})
{
{
var request = new RestRequest("post", Method.POST);
request.AddParameter("param1", "param1");
var response = await client.Execute<HttpBinResponse>(request);
Assert.NotNull(response.Data);
Assert.NotNull(response.Data.Form);
Assert.True(response.Data.Form.ContainsKey("param1"));
Assert.Equal("param1", response.Data.Form["param1"]);
}
{
var request = new RestRequest("post", Method.POST);
request.AddParameter("param1", "param1+");
var response = await client.Execute<HttpBinResponse>(request);
Assert.NotNull(response.Data);
Assert.NotNull(response.Data.Form);
Assert.True(response.Data.Form.ContainsKey("param1"));
Assert.Equal("param1+", response.Data.Form["param1"]);
}
}
}
示例14: Cannot_Set_Empty_Host_Header
public void Cannot_Set_Empty_Host_Header()
{
var request = new RestRequest();
var exception = Assert.Throws<ArgumentException>(() => request.AddHeader("Host", string.Empty));
Assert.AreEqual("value", exception.ParamName);
}
示例15: Writes_Response_To_Stream
public void Writes_Response_To_Stream()
{
const string baseUrl = "http://localhost:8888/";
using (SimpleServer.Create(baseUrl, Handlers.FileHandler))
{
string tempFile = Path.GetTempFileName();
using (var writer = File.OpenWrite(tempFile))
{
var client = new RestClient(baseUrl);
var request = new RestRequest("Assets/Koala.jpg");
request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer);
var response = client.DownloadData(request);
Assert.Null(response);
}
var fromTemp = File.ReadAllBytes(tempFile);
var expected = File.ReadAllBytes(Environment.CurrentDirectory + "\\Assets\\Koala.jpg");
Assert.Equal(expected, fromTemp);
}
}