本文整理汇总了C#中RequestType.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# RequestType.ToString方法的具体用法?C# RequestType.ToString怎么用?C# RequestType.ToString使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RequestType
的用法示例。
在下文中一共展示了RequestType.ToString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReturnsAMessageWithTheCorrectDataTypeWhenRequestingA
public void ReturnsAMessageWithTheCorrectDataTypeWhenRequestingA(RequestType requestType)
{
var retriever = new ResponseFileRetriever();
var response = retriever.GetResponse(requestType);
var datatypes = response.GetElementsByTagName("DataType");
var dataType = "WRONG";
if (datatypes.Count > 0)
dataType = datatypes.Item(0).InnerText;
Assert.AreEqual(requestType.ToString(), dataType);
}
示例2: WithNotificationHttpMethod
public PutObjectPersistedNotificationRegistrationSpectraS3Request WithNotificationHttpMethod(RequestType? notificationHttpMethod)
{
this._notificationHttpMethod = notificationHttpMethod;
if (notificationHttpMethod != null)
{
this.QueryParams.Add("notification_http_method", notificationHttpMethod.ToString());
}
else
{
this.QueryParams.Remove("notification_http_method");
}
return this;
}
开发者ID:rpmoore,项目名称:ds3_net_sdk,代码行数:13,代码来源:PutObjectPersistedNotificationRegistrationSpectraS3Request.cs
示例3: SendAddressBookRequest
/// <summary>
/// Send the request to address book server endpoint.
/// </summary>
/// <param name="requestBody">The request body.</param>
/// <param name="requestType">The type of the request.</param>
/// <param name="cookieChange">Whether the session context cookie is changed.</param>
/// <returns>The returned chunked response.</returns>
private ChunkedResponse SendAddressBookRequest(IRequestBody requestBody, RequestType requestType, bool cookieChange = true)
{
byte[] rawBuffer = null;
ChunkedResponse chunkedResponse = null;
// Send the execute HTTP request and get the response
HttpWebResponse response = MapiHttpAdapter.SendMAPIHttpRequest(this.site, this.addressBookUrl, this.userName, this.domainName, this.password, requestBody, requestType.ToString(), AdapterHelper.SessionContextCookies);
rawBuffer = MapiHttpAdapter.ReadHttpResponse(response);
string responseCode = response.Headers["X-ResponseCode"];
this.site.Assert.AreEqual<uint>(0, uint.Parse(responseCode), "The request to the address book server should be executed successfully!");
// Read the HTTP response buffer and parse the response to correct format
chunkedResponse = ChunkedResponse.ParseChunkedResponse(rawBuffer);
response.GetResponseStream().Close();
if (cookieChange)
{
AdapterHelper.SessionContextCookies = response.Cookies;
}
return chunkedResponse;
}
示例4: Request
private string Request(RequestType reqType, string url, string postData, Dictionary<string, string> requestHeaders)
{
var request = GetWebRequest(url);
var responseData = "";
if (request == null)
return "";
request.Method = reqType.ToString();
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = CookieContainer;
request.UserAgent = RefreshUserAgent();
request.KeepAlive = true;
request.AllowAutoRedirect = AllowAutoRedirect;
request.Referer = Referer;
request.Timeout = TimeoutInterval;
if (reqType == RequestType.POST)
request.ContentLength = postData.Length;
if (requestHeaders != null)
{
foreach (var item in requestHeaders)
{
switch (item.Key)
{
case "Accept":
request.Accept = item.Value;
break;
case "Content-Type":
request.ContentType = item.Value;
break;
default:
request.Headers.Add(item.Key, item.Value);
break;
}
}
}
//Decode Response
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
if (reqType == RequestType.POST)
{
var stOut = new StreamWriter(request.GetRequestStream());
stOut.Write(postData);
stOut.Flush();
stOut.Close();
}
try
{
var response = (HttpWebResponse)request.GetResponse();
response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
// ReSharper disable once AssignNullToNotNullAttribute
var responseReader = new StreamReader(response.GetResponseStream(), _utf8Encoding, true);
responseData = responseReader.ReadToEnd();
response.Close();
responseReader.Close();
CollectCookies(request, response);
}
catch (Exception ex)
{
Console.WriteLine("Failed: " + ex.Message);
}
return responseData;
}
示例5: Send
//---- Private Methods ----//
/// <summary>Performs a request to the backend.</summary>
/// <param name="type">The request type(Get, Post, Update, Delete)</param>
/// <param name="command">Command that is pasted after the url to backend. For example: "localhost:8000/api/" + command</param>
/// <param name="wwwForm">A WWWForm to send with the request</param>
/// <param name="onResponse">A callback which will be called when we retrieve the response</param>
/// <param name="authToken">An optional authToken which, when set will be put in the Authorization header</param>
public void Send(RequestType type, string command, WWWForm wwwForm, RequestResponseDelegate onResponse = null, string authToken = "") {
WWW request;
#if UNITY_5_PLUS
Dictionary<string, string> headers;
#else
Hashtable headers;
#endif
byte[] postData;
string url = BackendUrl + command;
if (Secure) {
url = url.Replace("http", "https");
}
if (wwwForm == null) {
wwwForm = new WWWForm();
postData = new byte[] { 1 };
} else {
postData = wwwForm.data;
}
headers = wwwForm.headers;
//make sure we get a json response
headers.Add("Accept", "application/json");
//also add the correct request method
headers.Add("X-UNITY-METHOD", type.ToString().ToUpper());
//also, add the authentication token, if we have one
if (authToken != "") {
//for more information about token authentication, see: http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
headers.Add("Authorization", "Token " + authToken);
}
request = new WWW(url, postData, headers);
System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
string callee = stackTrace.GetFrame(1).GetMethod().Name;
StartCoroutine(HandleRequest(request, onResponse, callee));
}
示例6: SubmitRequest
/// <summary>
/// Private helper that actually creates the request, submits it, and processes the result
/// </summary>
private AzureManagementResponse SubmitRequest(Uri uri, RequestType type, string version, string body)
{
// Submit a request to the Azure management web API
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = type.ToString();
request.Headers.Add("x-ms-version", version);
request.ContentType = "application/xml";
request.ClientCertificates.Add(this.certificate);
WebResponse response;
try
{
// If we have data to send, send it.
if (body != null)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = bytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
// Get a response
response = request.GetResponse();
}
catch (Exception ex)
{
if (ex is WebException)
{
WebException webEx = (WebException)ex;
HttpWebResponse webResponse = (HttpWebResponse)webEx.Response;
if (webResponse != null)
{
switch (webResponse.StatusCode)
{
case HttpStatusCode.Conflict:
throw new InvalidOperationException("The Windows Azure management service has reported a conflict. This usually indicates an existing deployment or an ongoing operation associated with this Windows Azure hosted service.");
case HttpStatusCode.Forbidden:
throw new InvalidOperationException("The Windows Azure management service has forbidden the request. This usually indicates a problem with uploading the Management Certificate.");
case HttpStatusCode.BadRequest:
string errorXml = null;
try
{
// Read the response XML
using (StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()))
{
errorXml = responseReader.ReadToEnd();
}
}
catch (Exception)
{
// Cannot get error detail
throw new InvalidOperationException("The Windows Azure management service has rejected the request from Windows HPC Server. This may indicate that the current instance limit for this Windows Azure subscription has been exceeded.");
}
// We get response body, try to get better format
if (!String.IsNullOrEmpty(errorXml) && !String.IsNullOrEmpty(errorXml.Trim()))
{
string code = null;
string message = null;
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(errorXml);
AzureManagementResponse azureResponse = new AzureManagementResponse(doc, webResponse);
XmlNode errorNode = azureResponse.GetXmlNode("Error");
code = azureResponse.GetXmlValue(errorNode, "Code");
message = azureResponse.GetXmlValue(errorNode, "Message");
}
catch (Exception)
{
// Cannot get better error code
throw new InvalidOperationException(string.Format("The Windows Azure management service rejected the HPC request: {0}", errorXml));
}
// Get error code and detail
throw new InvalidOperationException(string.Format("The Windows Azure management service has rejected the HPC request. The error ({0}) message is: {1}", code, message));
}
else
{
throw new InvalidOperationException(string.Format("The Windows Azure management service has rejected the request from Windows HPC Server. This may indicate that the current instance limit for this Windows Azure subscription has been exceeded."));
}
}
}
}
throw new AzureManagementException(ex, uri.AbsoluteUri, body);
}
// Read the response XML
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string xml = reader.ReadToEnd();
// Some actions will return an XML blob, while others will
// return nothing
XmlDocument xmlDoc = new XmlDocument();
//.........这里部分代码省略.........
示例7: Fetch
protected async Task<JsonValue> Fetch(
Uri endPoint,
RequestType requestType,
bool needsToken,
CancellationToken cancel,
IProgress<ProgressChangedEventArgs> progress = null,
IDictionary<string, string> postData = null,
KeyValuePair<string,string>? overrideAuth = null)
{
if (endPoint == null)
throw new ArgumentNullException("endPoint");
var wc = new WebClient();
if (needsToken && !Credentials.HasValue)
throw new InvalidOperationException("Cannot access this part of the Quizlet service without logging in.");
wc.Headers["User-Agent"] = "FlashcardsWP8/0.1 (" + Environment.OSVersion + "; .NET " + Environment.Version + ")";
// Overriding is used for basic authentication for OAuth process.
bool useClientID = false;
if (overrideAuth != null)
wc.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(overrideAuth.Value.Key + ":" + overrideAuth.Value.Value));
else if (Credentials != null)
wc.Headers["Authorization"] = "Bearer " + Credentials.Value.ApiToken;
else
useClientID = true;
try {
string result;
if (requestType == RequestType.Get) {
var uri = new Uri(ServiceUri, endPoint);
uri = new Uri(uri + (uri.Query == "" ? "?" : "&") + "client_id=" + clientID);
result = await wc.DownloadStringAsTask(uri, cancel, progress);
} else {
var sb = new StringBuilder();
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
wc.Encoding = Encoding.UTF8;
if (postData != null) {
if (useClientID)
postData["client_id"] = clientID;
foreach (var kvp in postData) {
if (sb.Length > 0)
sb.Append('&');
sb.Append(kvp.Key).Append('=').Append(Uri.EscapeDataString(kvp.Value));
}
}
result = await wc.UploadStringAsTask(new Uri(ServiceUri, endPoint), requestType.ToString().ToUpperInvariant(), sb.ToString(), cancel, progress);
}
JsonValue json = null;
// In case of HTTP status 204 (no content). This is produced, for example, as the result of
// a DELETE call to an endpoint.
if (!string.IsNullOrWhiteSpace(result))
json = JsonValue.Parse(new StringReader(result));
return json;
} catch (WebException e) {
// The Quizlet API returns a JSON document explaining the error if there is one,
// so try to use that if possible.
try {
if (e.Response != null) {
var response = (e.Response as HttpWebResponse).GetResponseStream();
using (var reader = new StreamReader(response)) {
var dict = JsonDictionary.FromValue(JsonValue.Parse(reader));
var ctx = new JsonContext();
var errorCode = ctx.FromJson<string>(dict["error"]);
var errorText = ctx.FromJson<string>(dict["error_description"]);
if (errorCode != null && errorText != null) {
switch (errorCode) {
case "invalid_access": throw new AccessDeniedException(errorText);
case "item_not_found": throw new ItemNotFoundException(errorText);
case "item_deleted": throw new ItemDeletedException(errorText);
default: throw new QuizletException(errorText);
}
}
}
}
throw new QuizletException(string.Format("Unable to contact the Quizlet server ({0}).", e.Message), e);
} catch (FormatException) {
// Not JSON or invalid - just wrap the original exception
throw new QuizletException(e.Message, e);
} catch (KeyNotFoundException) {
throw new QuizletException(e.Message, e);
}
}
}
示例8: InitializeHTTPHeader
/// <summary>
/// Initialize HTTP Header
/// </summary>
/// <param name="requestType">The request type</param>
/// <param name="clientInstance">The string of the client instance</param>
/// <param name="counter">The counter</param>
/// <returns>The web header collection</returns>
public static WebHeaderCollection InitializeHTTPHeader(RequestType requestType, string clientInstance, int counter)
{
WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
webHeaderCollection.Add("X-ClientInfo", ConstValues.ClientInfo);
webHeaderCollection.Add("X-RequestId", clientInstance + ":" + counter.ToString());
webHeaderCollection.Add("X-ClientApplication", ConstValues.ClientApplication);
webHeaderCollection.Add("X-RequestType", requestType.ToString());
return webHeaderCollection;
}
示例9: MakeRequest
public string MakeRequest(string relativeUrl, RequestType requestType)
{
HttpWebRequest httpRequest = BuildRelativeBaseHttpWebRequest(relativeUrl, requestType.ToString().ToUpperInvariant());
return ExecuteWebRequest(httpRequest);
}
示例10: MessageBuilder
/// <summary>
/// Creates a new instance of the <see cref="MessageBuilder"/> class
/// used to build a request message.
/// </summary>
/// <param name="messageType">The <see cref="RequestType"/> of the message</param>
/// <param name="key">The <see cref="Key"/> used to authorize and encrypt the message</param>
public MessageBuilder(RequestType messageType, Key key)
: this(messageType.ToString(), key, true)
{
}
示例11: SendRequest
public void SendRequest(List<WebRequestParameters> paras, bool postByByte, out bool succeed, RequestType requestType= RequestType.POST)
{
if(string.IsNullOrEmpty(this.ApiUrl))
{
throw new Exception("URI 不能为空");
}
string returnRes = string.Empty;
string postData = string.Empty;
if (paras != null && paras.Count > 0)
{
foreach (WebRequestParameters d in paras)
{
string pdata = "";
if (!string.IsNullOrEmpty(d.Value))
{
pdata = d.Value;
if (d.URLEncodeParameter)
{
pdata = System.Web.HttpUtility.UrlEncode(pdata);
}
}
if (string.IsNullOrEmpty(pdata))
{
pdata = "";
}
if (postData == string.Empty)
{
postData = string.Format("{0}={1}", d.Name, pdata);
}
else
{
postData += "&" + string.Format("{0}={1}", d.Name, pdata);
}
}
}
HttpWebRequest request = null;
HttpWebResponse response = null;
succeed = false;
try
{
if(requestType== RequestType.GET)
{
this.ServerUri = new Uri(this.ApiUrl+"?"+ postData);
}else
{
if(this.ServerUri==null)
{
this.ServerUri = new Uri(this.ApiUrl);
}
}
request = (HttpWebRequest)WebRequest.Create(this.ServerUri);
//request.PreAuthenticate = true;
//request.Credentials = new NetworkCredential(this.UserName, this.Password);
//request.AllowAutoRedirect = false;
request.Accept = "*/*";
request.KeepAlive = true;
request.Timeout = 10000 * 6 * 15;
request.Method = requestType.ToString();
request.ContentType = "application/x-www-form-urlencoded";
//string cookieheader = string.Empty;
//CookieContainer cookieCon = new CookieContainer();
//request.CookieContainer = cookieCon;
//request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
//if (cookieheader.Equals(string.Empty))
//{
// cookieheader = request.CookieContainer.GetCookieHeader(this.ServerUri);
//}
//else
//{
// request.CookieContainer.SetCookies(this.ServerUri, cookieheader);
//}
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
//Post string to the server
if (!postByByte)
{
if(requestType== RequestType.POST)
{
request.ContentLength = Encoding.UTF8.GetByteCount(postData);
System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream(), new UTF8Encoding(false));
sw.Write(postData);
sw.Close();
}
}
else
{
//Post byte to server
Encoding encoding = Encoding.GetEncoding("utf-8");
Byte[] bytePost = encoding.GetBytes(postData);
request.ContentLength = bytePost.Length;
//.........这里部分代码省略.........
示例12: SetRequestType
public void SetRequestType(RequestType type)
{
requestLabel.Markup = "<span color='lightblue'>" + Catalog.GetString("Request type:") + " </span>";
if(type == RequestType.None)
requestLabel.Markup += "<span color='orange'><b>" + Catalog.GetString("No Request") + "</b></span>";
else
requestLabel.Markup += "<span color='orange'><b>" + type.ToString() + "</b></span>";
}
示例13: GetHttpPage
/// <summary>
/// Navigates to a HTTP Page
/// </summary>
/// <param name="url">web url to retrieve</param>
/// <param name="requestType">Request Type, GET/POST/PUT/DELETE</param>
/// <param name="contentType">This is for POST's only, either XML or YAML</param>
/// <param name="postData">Data to POST, if a POST is being performed, otherwise this is ignored</param>
/// <returns>HTML response from server</returns>
public string GetHttpPage(Uri url, RequestType requestType, ContentType contentType, string postData)
{
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Timeout = 15000;
wr.ServicePoint.Expect100Continue = false;
wr.KeepAlive = false;
wr.Accept = "application/xml";
wr.ReadWriteTimeout = 35000;
wr.Method = requestType.ToString().ToUpper();
wr.CookieContainer = new CookieContainer();
if (_CC != null)
wr.CookieContainer.Add(_CC);
// if we have data to post, then be sure to send the data properly
if (postData != null && postData.Length > 0)
{
Encoding encoding = Encoding.UTF8;
byte[] outByte = encoding.GetBytes(postData);
// Set the content type of the data being posted.
if (contentType == ContentType.Xml)
wr.ContentType = "application/xml";
else if (contentType == ContentType.Yaml)
wr.ContentType = "application/x-yaml";
// Set the content length of the string being posted.
wr.ContentLength = outByte.Length;
Stream outStream = wr.GetRequestStream();
outStream.Write(outByte, 0, outByte.Length);
// Close the Stream object.
outStream.Flush();
outStream.Close();
}
// get the response back from the server
HttpWebResponse response = null;
string Result = string.Empty;
try
{
wr.Timeout = 120000;
//Console.WriteLine(wr.Timeout);
response = (HttpWebResponse)wr.GetResponse();
if ((wr.CookieContainer.Count > 0))
_CC = wr.CookieContainer.GetCookies(wr.RequestUri);
Result = ReadResponseStream(response);
}
catch (WebException webEx)
{
_Error = ReadResponseStream((HttpWebResponse)webEx.Response);
_Error = ParseError(_Error);
// re-throw the error so the user knows there was an issue
throw;
}
finally
{
if (response != null)
response.Close();
}
return Result;
}
示例14: PostXmlToUrl
public static string PostXmlToUrl(string url, NameValueCollection col, RequestType type)
{
string returnmsg = "";
string inputXML = getXMLInput(col, Encoding.UTF8);
using (System.Net.WebClient wc = new System.Net.WebClient())
{
returnmsg = wc.UploadString(url, type.ToString(), inputXML);
}
return returnmsg;
}
示例15: AzureRequest
internal AzureResponse AzureRequest(RequestType requestType, string payload, string uriFormat, params object[] args)
{
var azureResponse = new AzureResponse();
var uri = new Uri(string.Format(uriFormat, new object[] { this.Credentials.SubscriptionID }.Concat(args).ToArray()));
this.LogDebug("Sending Azure API {0} request to \"{1}\"...", requestType.ToString().ToUpper(), uri);
var req = (HttpWebRequest)HttpWebRequest.Create(uri);
if (requestType == RequestType.Post)
req.Method = "POST";
else if (requestType == RequestType.Delete)
req.Method = "DELETE";
else
req.Method = "GET";
req.Headers.Add("x-ms-version", OperationVersion);
req.ClientCertificates.Add(this.Credentials.Certificate);
req.ContentType = "application/xml";
if (!string.IsNullOrEmpty(payload))
{
this.LogDebug("Writing request data...");
var buffer = Encoding.UTF8.GetBytes(payload);
req.ContentLength = buffer.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
}
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException ex)
{
resp = (HttpWebResponse)ex.Response;
}
azureResponse.StatusCode = resp.StatusCode;
azureResponse.Headers = resp.Headers;
if (resp.ContentLength > 0)
{
using (XmlReader reader = XmlReader.Create(resp.GetResponseStream()))
{
this.LogDebug("Parsing Azure API XML response...");
azureResponse.Document = XDocument.Load(reader);
azureResponse.ErrorMessage = (string)azureResponse.Document.Descendants(ns + "Message").FirstOrDefault();
azureResponse.ErrorCode = (string)azureResponse.Document.Descendants(ns + "Code").FirstOrDefault();
AzureResponse.OperationStatusResult status;
var statusElement = azureResponse.Document.Root.Element(ns + "Status");
if (statusElement != null && Enum.TryParse<AzureResponse.OperationStatusResult>(statusElement.Value, true, out status))
azureResponse.OperationStatus = status;
this.LogDebug("Azure API XML response parsed.");
}
}
return azureResponse;
}