本文整理汇总了C#中RestClient类的典型用法代码示例。如果您正苦于以下问题:C# RestClient类的具体用法?C# RestClient怎么用?C# RestClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
RestClient类属于命名空间,在下文中一共展示了RestClient类的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: Handles_Default_Root_Element_On_No_Error
public void Handles_Default_Root_Element_On_No_Error()
{
Uri baseUrl = new Uri("http://localhost:8888/");
using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.Generic<ResponseHandler>()))
{
RestClient client = new RestClient(baseUrl);
RestRequest request = new RestRequest("success")
{
RootElement = "Success"
};
request.OnBeforeDeserialization = resp =>
{
if (resp.StatusCode == HttpStatusCode.NotFound)
{
request.RootElement = "Error";
}
};
IRestResponse<Response> response = client.Execute<Response>(request);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
Assert.AreEqual("Works!", response.Data.Message);
}
}
示例3: Handles_GET_Request_404_Error
public void Handles_GET_Request_404_Error()
{
var client = new RestClient(BaseUrl);
var request = new RestRequest("StatusCode/404");
var response = client.Execute(request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
示例4: TwitterHelper
public TwitterHelper()
{
_twitterSettings = Helper.LoadSetting<TwitterAccess>(Constants.TwitterAccess);
if (_twitterSettings == null || String.IsNullOrEmpty(_twitterSettings.AccessToken) ||
String.IsNullOrEmpty(_twitterSettings.AccessTokenSecret))
{
return;
}
_authorized = true;
_credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.ConsumerKey,
ConsumerSecret = TwitterSettings.ConsumerKeySecret,
Token = _twitterSettings.AccessToken,
TokenSecret = _twitterSettings.AccessTokenSecret,
Version = TwitterSettings.OAuthVersion,
};
_client = new RestClient
{
Authority = "http://api.twitter.com",
HasElevatedPermissions = true
};
}
示例5: Handles_Server_Timeout_Error_Async
public void Handles_Server_Timeout_Error_Async()
{
const string baseUrl = "http://localhost:8888/";
ManualResetEvent resetEvent = new ManualResetEvent(false);
using (SimpleServer.Create(baseUrl, TimeoutHandler))
{
RestClient client = new RestClient(baseUrl);
RestRequest request = new RestRequest("404")
{
Timeout = 500
};
IRestResponse response = null;
client.ExecuteAsync(request, responseCb =>
{
response = responseCb;
resetEvent.Set();
});
resetEvent.WaitOne();
Assert.NotNull(response);
Assert.AreEqual(response.ResponseStatus, ResponseStatus.TimedOut);
Assert.NotNull(response.ErrorException);
Assert.IsInstanceOf<WebException>(response.ErrorException);
Assert.AreEqual(response.ErrorException.Message, "The request timed-out.");
}
}
示例6: BuildEndpoint
public Uri BuildEndpoint(RestClient client)
{
var sb = new StringBuilder();
var path = Path.IsNullOrBlank()
? client.Path.IsNullOrBlank() ? "" : client.Path
: Path;
var versionPath = VersionPath.IsNullOrBlank()
? client.VersionPath.IsNullOrBlank() ? "" : client.VersionPath
: VersionPath;
var skipAuthority = client.Authority.IsNullOrBlank();
sb.Append(skipAuthority ? "" : client.Authority);
sb.Append(skipAuthority ? "" : client.Authority.EndsWith("/") ? "" : "/");
sb.Append(skipAuthority ? "" : versionPath.IsNullOrBlank() ? "" : versionPath);
if (!skipAuthority && !versionPath.IsNullOrBlank())
{
sb.Append(versionPath.EndsWith("/") ? "" : "/");
}
sb.Append(path.IsNullOrBlank() ? "" : path.StartsWith("/") ? path.Substring(1) : path);
Uri uri;
Uri.TryCreate(sb.ToString(), UriKind.RelativeOrAbsolute, out uri);
// [DC]: If the path came in with parameters attached, we should scrub those
WebParameterCollection parameters;
uri = uri.UriMinusQuery(out parameters);
foreach (var parameter in parameters)
{
Parameters.Add(parameter);
}
return uri;
}
示例7: 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.");
}
}
示例8: CreateClient
public IRestClient CreateClient()
{
var client = new RestClient();
client.HttpClientFactory = this.GetHttpClientFactory();
client.IgnoreResponseStatusCode = true;
return client;
}
示例9: GetFriends
public static void GetFriends(EventHandler<FriendsListEventArgs> callback)
{
var serializer = new Hammock.Serialization.HammockDataContractJsonSerializer();
RestClient client = new RestClient
{
Authority = baseUrl,
Timeout = new TimeSpan(0, 0, 0, _timeOut),
Serializer = serializer,
Deserializer = serializer
};
RestRequest request = new RestRequest
{
Path = "GetFriends" + "?timestamp=" + DateTime.Now.Ticks.ToString(),
Timeout = new TimeSpan(0, 0, 0, _timeOut)
};
friendscallback = callback;
try
{
client.BeginRequest(request, new RestCallback<List<Friend>>(GetFriendsCallback));
}
catch (Exception ex)
{
friendscallback.Invoke(null, new FriendsListEventArgs() { Friends = null, Error = new WebException("Communication Error!", ex) });
}
}
示例10: DelegateWith
public static RestRequest DelegateWith(RestClient client, RestRequest request)
{
if(request == null)
{
throw new ArgumentNullException("request");
}
if(!request.Method.HasValue)
{
throw new ArgumentException("Request must specify a web method.");
}
var method = request.Method.Value;
var credentials = (OAuthCredentials)request.Credentials;
var url = request.BuildEndpoint(client).ToString();
var workflow = new OAuthWorkflow(credentials);
var uri = new Uri(client.Authority);
var realm = uri.Host;
var enableTrace = client.TraceEnabled || request.TraceEnabled;
var info = workflow.BuildProtectedResourceInfo(method, request.GetAllHeaders(), url);
var query = credentials.GetQueryFor(url, request, info, method, enableTrace);
((OAuthWebQuery) query).Realm = realm;
var auth = query.GetAuthorizationContent();
var echo = new RestRequest();
echo.AddHeader("X-Auth-Service-Provider", url);
echo.AddHeader("X-Verify-Credentials-Authorization", auth);
return echo;
}
示例11: Index
public ActionResult Index()
{
var restConfig = RestConfig.Current;
if (string.IsNullOrEmpty(restConfig.UserId))
return RedirectToAction("Authorize");
var client = new RestClient {Authority = restConfig.BaseUrl};
var request = new RestRequest
{
Path = string.Format("users/{0}/queues/instant", restConfig.UserId),
Credentials = OAuthCredentials.ForProtectedResource(
restConfig.OAuthKey, restConfig.OAuthSharedSecret,
restConfig.OAuthToken, restConfig.OAuthTokenSecret)
};
var response = client.Request(request);
if (response.StatusCode == HttpStatusCode.OK)
{
var xml = XDocument.Parse(response.Content);
var items = from i in xml.Descendants("queue_item")
select new Movie
{
Title = (string) i.Descendants("title").Attributes("regular").FirstOrDefault(),
Thumbnail = (string)i.Descendants("box_art").Attributes("small").FirstOrDefault(),
ReleaseYear = (string)i.Descendants("release_year").FirstOrDefault(),
Link = (string)i.Descendants("link").Where(x => (string) x.Attribute("rel") == "alternate").Attributes("href").FirstOrDefault()
};
var model = new {Response = response, Items = items}.ToExpando();
return View(model);
}
return View(new {Response = response, Items = (object) null}.ToExpando());
}
示例12: DropboxFileSystem
public DropboxFileSystem (Session session)
{
this.session = session;
sharedClient = new RestClient (session);
UserId = session.UserIds.FirstOrDefault () ?? "Unknown";
FileExtensions = new System.Collections.ObjectModel.Collection<string> ();
}
示例13: Details
public ActionResult Details(string code)
{
RestClient<Product> productsRestClient = new RestClient<Product>("http://localhost:3001/");
var product = productsRestClient.Get("products/code/" + code).Result;
// TODO: Fix this in EF
product.Supplier = new Supplier
{
Id = product.SupplierId,
Name = "My Supplier"
};
var productViewModel = new ProductViewModel()
{
Id = product.Id,
Code = product.Code,
Name = product.DisplayName,
Price = product.UnitPrice,
SupplierName = product.Supplier.Name
};
ProductViewModel another = Mapper.Map<ProductViewModel>(product);
return View(another);
}
示例14: GetFavorites
public RestResponse GetFavorites(string user, int page, int pageSize)
{
// Documentation for GET /favorites
// https://dev.twitter.com/docs/api/1/get/favorites
// Create the REST Client
var client = new RestClient {Authority = "http://api.twitter.com/1"};
// Create the REST Request
var request = new RestRequest {Path = "favorites.json", Method = WebMethod.Get};
request.AddParameter("id", user);
request.AddParameter("page", page.ToString());
request.AddParameter("count", pageSize.ToString());
// Set API authentication tokens
var appSettings = ConfigurationManager.AppSettings;
request.Credentials = OAuthCredentials.ForProtectedResource(
appSettings["ConsumerKey"], appSettings["ConsumerSecret"], appSettings["Token"],
appSettings["TokenSecret"]);
// Make request
var response = client.Request(request);
return response;
}
示例15: ApplicationBarIconButton_Click
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
RestClient client2 = new RestClient
{
Authority = "https://graph.facebook.com/",
};
RestRequest request2 = new RestRequest
{
Path = "/me/feed?message=" + WatermarkTB.Text
};
if (imgstream != null)
{
string albumId = (string)settings["facebook_photo"];
request2 = new RestRequest
{
Path = albumId + "/photos?message=" + WatermarkTB.Text
};
request2.AddFile("photo", "image.jpg", imgstream);
}
request2.AddField("access_token", (string)settings["facebook_token"]);
var callback = new RestCallback(
(restRequest, restResponse, userState) =>
{
// Callback when signalled
}
);
client2.BeginRequest(request2, callback);
MessageBox.Show("Share successfully.", "Thanks", MessageBoxButton.OK);
this.NavigationService.GoBack();
}