本文整理汇总了C#中RestSharp.RestRequest.AddHeader方法的典型用法代码示例。如果您正苦于以下问题:C# RestRequest.AddHeader方法的具体用法?C# RestRequest.AddHeader怎么用?C# RestRequest.AddHeader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RestSharp.RestRequest
的用法示例。
在下文中一共展示了RestRequest.AddHeader方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddTask
public void AddTask(Task newTask)
{
try
{
var addedTask = new AddedTask
{
type = newTask.Type,
text = newTask.Text,
date = newTask.Date
};
var request = new RestRequest("/user/tasks", Method.POST);
request.AddHeader("x-api-key", _apiToken);
request.AddHeader("x-api-user", _apiUser);
//var jsonObj = JsonConvert.SerializeObject(addedTask);
request.RequestFormat = DataFormat.Json;
request.AddBody(addedTask);
var response = _restClient.Execute(request);
var error = response.ErrorMessage;
}
catch (Exception ex)
{
var message = ex.Message;
}
}
示例2: ActivateFeature
public string ActivateFeature(string baseSiteUrl, string user, string password, string domain)
{
if (baseSiteUrl.EndsWith("/"))
baseSiteUrl += "_api/";
else
baseSiteUrl += "/_api/";
RestClient rc = new RestClient(baseSiteUrl);
NetworkCredential nCredential = new NetworkCredential(user, password, domain);
rc.Authenticator = new NtlmAuthenticator(nCredential);
RestRequest request = new RestRequest("contextinfo?$select=FormDigestValue", Method.POST);
request.AddHeader("Accept", "application/json;odata=verbose");
request.AddHeader("Body", "");
string returnedStr = rc.Execute(request).Content;
int startPos = returnedStr.IndexOf("FormDigestValue", StringComparison.Ordinal) + 18;
int length = returnedStr.IndexOf(@""",", startPos, StringComparison.Ordinal) - startPos;
string formDigestValue = returnedStr.Substring(startPos, length);
request = new RestRequest("web/features/add('de646322-53f3-474d-96bf-0ea3670a0722',false)", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Accept", "application/json;odata=verbose");
//request.AddHeader("Body", "");
request.AddHeader("Content-Type", "application/json;odata=verbose");
request.AddHeader("X-RequestDigest", formDigestValue);
IRestResponse response = rc.Execute(request);
string content = response.Content;
return content;
}
示例3: CallApi
/// <summary>
/// Makes the HTTP request (Sync).
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="authSettings">Authentication settings.</param>
/// <returns>Object</returns>
public Object CallApi(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, String[] authSettings)
{
var request = new RestRequest(path, method);
UpdateParamsForAuth(queryParams, headerParams, authSettings);
// add default header, if any
foreach(var defaultHeader in _defaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(var param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(var param in queryParams)
request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
// add form parameter, if any
foreach(var param in formParams)
request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
// add file parameter, if any
foreach(var param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) // http body (model) parameter
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
return (Object)RestClient.Execute(request);
}
示例4: Request
public string Request(RestSharp.Method method, string endPoint, Dictionary<string,object> headers, Dictionary<string, object> parameters, Dictionary<string, object> queryParameters, string body)
{
RestClient client = new RestClient(baseURL);
RestRequest request = new RestRequest(endPoint, method);
client.Authenticator = authenticator;
foreach (var key in headers.Keys)
{
if(headers[key].GetType().ToString().StartsWith("System.Collections.Generics.List"))
{
request.AddHeader(key,JsonConvert.SerializeObject(headers[key]));
}
else
{
request.AddHeader(key,headers[key].ToString());
}
}
foreach (var key in parameters.Keys)
{
request.AddParameter(key, parameters[key]);
}
foreach (var key in queryParameters.Keys)
{
if (headers[key].GetType().ToString().StartsWith("System.Collections.Generics.List"))
{
request.AddQueryParameter(key, JsonConvert.SerializeObject(queryParameters[key]));
}
else
{
request.AddQueryParameter(key, queryParameters[key].ToString());
}
}
var response = client.Execute(request);
return response.Content;
}
示例5: AuthanticateUser
/// <summary>
/// 验证用户登录
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="userPass">密码</param>
/// <returns></returns>
public Task<User> AuthanticateUser(string userName,string userPass)
{
var request = new RestRequest("Authentication");
var passMD5 = MD5Core.GetHashString(userPass).ToLowerInvariant();
request.AddHeader("UserName", userName);
request.AddHeader("Key", HMACSHAEncryptor.GetHASMString(passMD5));
var taskCompletionSource=new TaskCompletionSource<User>();
User user = null;
AppClient.ExecuteAsyncGet(request,(response,e)=>{
if(response.StatusCode==HttpStatusCode.OK)
{
response.ContentEncoding = "utf-8";
var resultJson = response.Content;
JObject jObject = JObject.Parse(resultJson);
var loginResult =int.Parse(jObject["Result"].ToString());
if (loginResult > 0)
{
user = new JsonParser().Deserialize<User>(resultJson);
}
}
taskCompletionSource.TrySetResult(user);
},"Get");
return taskCompletionSource.Task;
}
示例6: StartHandling
/// <summary>
/// Inicia processamento do pedido
/// </summary>
public void StartHandling()
{
string strOrderId = "v00000000XXXX-01";
string requestRoute = "/oms/pvt/orders/" + strOrderId + "/start-handling";
#region RestSharp
//Utilizando RestSharp (http://restsharp.org/)
var request = new RestRequest(requestRoute, Method.POST);
request.AddHeader("X-VTEX-API-AppKey", strAppKey);
request.AddHeader("X-VTEX-API-AppToken", strAppToken);
// execute the request
var response = vtexServiceRestClient.Execute(request);
var content = response.Content; // raw content as string
#endregion
#region WebClient
//System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(baseURL + "pvt/orders/" + strOrderId + "/start-handling");
//objRequest.Headers = HeaderCollection;
//objRequest.Accept = "application/json";
//objRequest.Method = "POST";
//StreamReader objStreamReader = new StreamReader(objRequest.GetResponse().GetResponseStream());
//string strResult = objStreamReader.ReadToEnd();
#endregion
}
示例7: newRestRequest
private static RestRequest newRestRequest(string todo)
{
RestRequest request = new RestRequest(todo);
request.AddHeader("Authorization", basicAutorization());
request.AddHeader("Accept", "application/vnd.github.v3+json");
return request;
}
示例8: PrepareRequest
// Creates and sets up a RestRequest prior to a call.
private RestRequest PrepareRequest(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams)
{
var request = new RestRequest(path, method);
// add path parameter, if any
foreach(var param in pathParams)
request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
// add DocuSign specific tracking headers
request.AddHeader("X-DocuSign-SDK", "C#");
// add header parameter, if any
foreach(var param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(var param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(var param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(var param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) // http body (model) parameter
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
return request;
}
示例9: IsLastedVersion
/// <summary>
/// 检查字典信息的版本信息
/// </summary>
/// <param name="lastedDate"></param>
/// <param name="typeTag">检查的类型:0/1/2 (种植/区域/各种害)</param>
/// <returns></returns>
public Task<bool> IsLastedVersion(DateTime lastedDate, int typeTag)
{
var request = new RestRequest("DictionaryVersion/?type="+typeTag);
request.AddHeader("UserId", base.UserId);
request.AddHeader("Token", base.Token);
request.AddHeader("VersionTime ", lastedDate.ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture));
bool isLasted = false;
var taskCompletionSource = new TaskCompletionSource<bool>();
AppClient.ExecuteAsyncGet(request, (response, e) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
response.ContentEncoding = "utf-8";
string resultJson = response.Content;
JObject json = JObject.Parse(resultJson);
bool resultValue = bool.Parse(json["IsLatest"].ToString());
if (resultValue)
{
isLasted = true;
}
}
taskCompletionSource.TrySetResult(isLasted);
}, "GET");
return taskCompletionSource.Task;
}
示例10: GetMapStationsData
async Task<String> GetMapStationsData()
{
var client = new RestClient("http://locator.shell.com.ru/front_end/smart_footprint_within_bounds?language=ru_RU&launch_countrycode=RU&service_id=6&selection_filter=TRUE%20AND%20flag_type_shell=TRUE%20%20AND%20not%20flag_type_crtm=TRUE");
var request = new RestRequest(Method.POST);
request.AddHeader("host", "locator.shell.com.ru");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("referer", "http://locator.shell.com.ru/?country=RU&language=ru_RU");
request.AddHeader("X-Requested-With", "XMLHttpRequest");
var formData = String.Format("authenticity_token={0}&ne={1}%2C{2}&sw={3}%2C{4}&zoom=6", authencityToken, ne_lat, ne_lng, sw_lat, sw_lng);
request.AddParameter("application/x-www-form-urlencoded", formData, ParameterType.RequestBody);
CookieContainer _cookieJar = new CookieContainer();
foreach (var cookie in cookies)
_cookieJar.Add(cookie);
client.CookieContainer = _cookieJar;
IRestResponse response = await client.ExecuteTaskAsync(request);
var result = response.Content.Trim();
if ( String.IsNullOrEmpty(result) || result == "null")
{
var s = String.Format("Не удалось получить json с заправками! StatusCode: {0}, ErrorMessage: {1}", response.StatusCode, response.ErrorMessage);
throw new ApplicationException(s, response.ErrorException);
}
return result;
}
示例11: BreakItemRoleInheritance
public void BreakItemRoleInheritance(string listTitle, string baseSiteUrl, string user, string password, string domain)
{
try
{
RestClient RC = new RestClient(baseSiteUrl);
NetworkCredential NCredential = new NetworkCredential(user, password, domain);
RC.Authenticator = new NtlmAuthenticator(NCredential);
RestRequest Request = new RestRequest("contextinfo?$select=FormDigestValue", Method.POST);
Request.AddHeader("Accept", "application/json;odata=verbose");
Request.AddHeader("Body", "");
string ReturnedStr = RC.Execute(Request).Content;
int StartPos = ReturnedStr.IndexOf("FormDigestValue") + 18;
int length = ReturnedStr.IndexOf(@""",", StartPos) - StartPos;
string FormDigestValue = ReturnedStr.Substring(StartPos, length);
Request = new RestRequest("web/lists/GetByTitle('" + listTitle + "')/getItemById(12)/breakroleinheritance", Method.POST);
// Request = new RestRequest("web/lists/GetByTitle('" + listTitle + "')/breakroleinheritance(true)", Method.POST);
Request.RequestFormat = DataFormat.Json;
Request.AddHeader("Accept", "application/json;odata=verbose");
Request.AddHeader("X-RequestDigest", FormDigestValue);
string content = RC.Execute(Request).Content;
//return "Permission breaked successfully";
}
catch (Exception)
{
throw;
}
}
示例12: Index
// GET: User
public ViewResult Index()
{
var token = _sessionHelper.GetToken();
if (token == "SessionIsNull")
return View("ErorrForm", new ErorrMessage { Message = "Нет токена" });
var clientUser = new RestClient(SiteConn.UserWebApiServer);
var getUser = new RestRequest($"User");
getUser.AddHeader("Authorization", token);
getUser.AddHeader("Content-Type", "application / json");
getUser.AddParameter("login", _sessionHelper.GetLogin());
var response = clientUser.Get<UserInfo>(getUser);
if(response.StatusCode == 0)
return View("ErorrForm", new ErorrMessage {Message = "Нет данных для отображения" });
if (response.Data == null)
return View("ErorrForm", new ErorrMessage { Message = "Нет данных для отображения" });
return View(response.Data);
}
示例13: Main
static void Main(string[] args)
{
if (!string.IsNullOrEmpty(Thumbprint) &&
!string.IsNullOrEmpty(GraphUrl) &&
!string.IsNullOrEmpty(ClientId) &&
!string.IsNullOrEmpty(Authority))
{
// Retrieve the certificate
var certificate = GetCertificate();
if (certificate != null)
{
// Get an access token
var token = GetAccessToken(certificate);
if (!string.IsNullOrEmpty(token.Result))
{
// Fetch the latest events
var client = new RestClient(GraphUrl);
var request = new RestRequest("/v1.0/users/{UserId or UserPrincipleName}/Events", Method.GET);
request.AddHeader("Authorization", "Bearer " + token.Result);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
var response = client.Execute(request);
var content = response.Content;
Console.WriteLine(content);
}
}
}
}
示例14: CallApiAsync
public async Task<Object> CallApiAsync(String Path, RestSharp.Method Method, Dictionary<String, String> QueryParams, String PostBody,
Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) {
var request = new RestRequest(Path, Method);
UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in this.defaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(KeyValuePair<string, string> param in HeaderParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(KeyValuePair<string, string> param in QueryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(KeyValuePair<string, string> param in FormParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(KeyValuePair<string, string> param in FileParams)
request.AddFile(param.Key, param.Value);
if (PostBody != null) {
request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter
}
return (Object) await restClient.ExecuteTaskAsync(request);
}
示例15: Authenticate
public void Authenticate()
{
RestClient rc = GetRestClient();
RestRequest request = new RestRequest("auth/v1.0/", Method.GET);
request.AddHeader("X-Auth-User", cfg.User);
request.AddHeader("X-Auth-Key", cfg.Authkey);
IRestResponse response = rc.Execute(request);
if (response.StatusCode == System.Net.HttpStatusCode.NoContent ||
response.StatusCode == System.Net.HttpStatusCode.OK)
{
foreach (Parameter hdr in response.Headers)
{
if (hdr.Name.Equals("X-Storage-Url"))
storageUrl = hdr.Value.ToString();
else if (hdr.Name.Equals("X-Auth-Token"))
authToken = hdr.Value.ToString();
}
cfg.Url = storageUrl + "/default";
}
else
{
throw new Exception("Authentication Failed. Error: " + response.ToString());
}
Debug.Print("Storage URL:" + storageUrl + "; " + "Auth Token: " + authToken);
}