本文整理汇总了C#中RestClient类的典型用法代码示例。如果您正苦于以下问题:C# RestClient类的具体用法?C# RestClient怎么用?C# RestClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
RestClient类属于命名空间,在下文中一共展示了RestClient类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
}
开发者ID:CL0SeY,项目名称:RestSharp,代码行数:28,代码来源:MultipartFormDataTests.cs
示例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);
}
}
开发者ID:CL0SeY,项目名称:RestSharp,代码行数:26,代码来源:StatusCodeTests.cs
示例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);
}
开发者ID:jonfuller,项目名称:RestSharp,代码行数:7,代码来源:StatusCodeTests.cs
示例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
};
}
开发者ID:pwattjaidee,项目名称:Thaibird,代码行数:30,代码来源:TwitterHelper.cs
示例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.");
}
}
开发者ID:godlzr,项目名称:RestSharp,代码行数:30,代码来源:NonProtocolExceptionHandlingTests.cs
示例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;
}
开发者ID:TheBerg,项目名称:f1-pco,代码行数:35,代码来源:RestRequest.cs
示例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.");
}
}
开发者ID:Bug2014,项目名称:RestSharp,代码行数:34,代码来源:AsyncTests.cs
示例8: CreateClient
public IRestClient CreateClient()
{
var client = new RestClient();
client.HttpClientFactory = this.GetHttpClientFactory();
client.IgnoreResponseStatusCode = true;
return client;
}
开发者ID:Ideine,项目名称:Xmf2,代码行数:7,代码来源:SpecificOAuth2RequestFactory.cs
示例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) });
}
}
开发者ID:253525306,项目名称:myfriendsaround,代码行数:26,代码来源:ServiceAgent.cs
示例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;
}
开发者ID:rakkeh,项目名称:hammock,代码行数:30,代码来源:OAuthCredentials.cs
示例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());
}
开发者ID:NashDotNet,项目名称:RestSamples,代码行数:31,代码来源:NetflixController.cs
示例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> ();
}
开发者ID:praeclarum,项目名称:Praeclarum,代码行数:7,代码来源:DropboxCoreFileSystem.cs
示例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);
}
开发者ID:alertbox,项目名称:stocksly,代码行数:25,代码来源:ProductsController.cs
示例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;
}
开发者ID:NashDotNet,项目名称:RestSamples,代码行数:25,代码来源:TwitterSamples.cs
示例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();
}
开发者ID:vapps,项目名称:HDStream,代码行数:32,代码来源:FacebookWrite.xaml.cs
示例16: 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);
}
}
开发者ID:propagated,项目名称:RestSharp,代码行数:26,代码来源:FileTests.cs
示例17: BuildEndpoint
public string 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);
var queryStringHandling = QueryHandling ?? client.QueryHandling ?? Hammock.QueryHandling.None;
switch (queryStringHandling)
{
case Hammock.QueryHandling.AppendToParameters:
return WebExtensions.UriMinusQuery(sb.ToString(), Parameters);
default:
return sb.ToString();
}
}
开发者ID:rakkeh,项目名称:hammock,代码行数:32,代码来源:RestRequest.cs
示例18: GetTwitterToken
private void GetTwitterToken()
{
var credentials = new OAuthCredentials
{
Type = OAuthType.RequestToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = Constants.ConsumerKey,
ConsumerSecret = Constants.ConsumerKeySecret,
Version = Constants.OAuthVersion,
CallbackUrl = Constants.CallbackUri
};
var client = new RestClient
{
Authority = "https://api.twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true,
SilverlightAcceptEncodingHeader = "gizp",
DecompressionMethods = DecompressionMethods.GZip,
};
var request = new RestRequest
{
Path = "/request_token"
};
client.BeginRequest(request, new RestCallback(TwitterRequestTokenCompleted));
}
开发者ID:CodeObsessed,项目名称:drumbleapp,代码行数:27,代码来源:TwitterAuthPage.xaml.cs
示例19: GetPublicationsIds
public PubMedPublicationIdsResult GetPublicationsIds(PubMedQueryFilter filter)
{
var restClient = new RestClient(ServiceURLs.ESearchBaseURL);
var restRequest = new RestRequest();
restRequest.AddParameter("db", databaseName, ParameterType.QueryString);
restRequest.AddParameter("retmode", "json", ParameterType.QueryString);
restRequest.AddParameter("retstart", (filter.Skip * filter.Take), ParameterType.QueryString);
restRequest.AddParameter("term", filter.Query, ParameterType.QueryString);
restRequest.AddParameter("retmax", filter.Take, ParameterType.QueryString);
if (filter.RelDate != DateTime.MinValue)
{
var pmDate = PubMedDateOperations.DatetimeToPubMedDate(filter.RelDate);
restRequest.AddParameter("reldate", pmDate, ParameterType.QueryString);
}
var waitTime = PubMedThrottler.GetWaitTime();
Thread.Sleep(waitTime);
var response = restClient.Execute<PubMedResponse>(restRequest).Result;
if (response.Data == null)
throw new Exception("No Response From The Server");
var result = new PubMedPublicationIdsResult();
result.PubMedIdCollection = new List<string>();
response.Data.esearchresult.idlist.ForEach(r => result.PubMedIdCollection.Add(r));
return result;
}
开发者ID:jn7163,项目名称:Pubmed.Explorer,代码行数:29,代码来源:PubMedRequest.cs
示例20: RetrieveTweets
private static string RetrieveTweets(string sinceId)
{
BasicAuthCredentials credentials = new BasicAuthCredentials
{
Username = WebConfigurationManager.AppSettings["ScreenName"],
Password = WebConfigurationManager.AppSettings["SuperTweetPassword"]
};
RestClient client = new RestClient
{
Authority = "http://api.supertweet.net",
VersionPath = "1"
};
string possibleSinceId = string.IsNullOrWhiteSpace(sinceId) ? "": string.Format("&since_id={0}", sinceId) ;
RestRequest request = new RestRequest
{
Credentials = credentials,
Path = string.Format("statuses/home_timeline.json?count=200&include_entities=false{0}", possibleSinceId)
};
RestResponse response = client.Request(request);
var content = response.Content;
return content;
}
开发者ID:zdam,项目名称:BatchedTweets,代码行数:25,代码来源:HomeController.cs
注:本文中的RestClient类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论