本文整理汇总了C#中System.Net.HttpWebRequest类的典型用法代码示例。如果您正苦于以下问题:C# HttpWebRequest类的具体用法?C# HttpWebRequest怎么用?C# HttpWebRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpWebRequest类属于System.Net命名空间,在下文中一共展示了HttpWebRequest类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: InsertSoapEnvelopeIntoWebRequest
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
开发者ID:neos1993,项目名称:-,代码行数:7,代码来源:SoapClientForPochtaRussia.cs
示例2: PostForm
private static HttpWebResponse PostForm(HttpWebRequest request , string userAgent, string contentType, byte[] formData)
{
if (request == null)
{
throw new NullReferenceException("request is not a http request");
}
// Set up the request properties.
request.Method = "POST";
request.ContentType = contentType;
request.UserAgent = userAgent;
request.CookieContainer = new CookieContainer();
request.ContentLength = formData.Length;
// You could add authentication here as well if needed:
// request.PreAuthenticate = true;
// request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
// request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));
// Send the form data to the request.
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
return request.GetResponse() as HttpWebResponse;
}
开发者ID:ccnuyan,项目名称:PowerPointQuestionnaire,代码行数:28,代码来源:FormUploader.cs
示例3: RunResponse
private string RunResponse(HttpWebRequest request)
{
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException wex)
{
if (wex.Response == null)
return JSON_ERROR;
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
return reader.ReadToEnd(); //expected error from JSON
}
}
}
var retVal = new StreamReader(stream: response.GetResponseStream()).ReadToEnd();
return retVal;
}
开发者ID:aplewe,项目名称:Amazing-Cloud-Search,代码行数:25,代码来源:WebHelper.cs
示例4: WebRequestEventArgs
/// <summary>
/// Initializes a new instance of the <see cref="WebRequestEventArgs"/> class
/// with the specified web request.
/// </summary>
/// <param name="request">The HTTP web request.</param>
/// <exception cref="ArgumentNullException">If <paramref name="request"/> is <see langword="null"/>.</exception>
public WebRequestEventArgs(HttpWebRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
_request = request;
}
开发者ID:charlyraffellini,项目名称:openstack.net,代码行数:13,代码来源:WebRequestEventArgs.cs
示例5: SignRequest
/// <summary>
/// Signs the specified HTTP request with a shared key.
/// </summary>
/// <param name="request">The HTTP request to sign.</param>
/// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
public void SignRequest(HttpWebRequest request, OperationContext operationContext)
{
CommonUtility.AssertNotNull("request", request);
if (!request.Headers.AllKeys.Contains(Constants.HeaderConstants.Date, StringComparer.Ordinal))
{
string dateString = HttpWebUtility.ConvertDateTimeToHttpString(DateTime.UtcNow);
request.Headers.Add(Constants.HeaderConstants.Date, dateString);
}
if (this.credentials.IsSharedKey)
{
string message = this.canonicalizer.CanonicalizeHttpRequest(request, this.accountName);
Logger.LogVerbose(operationContext, SR.TraceStringToSign, message);
StorageAccountKey accountKey = this.credentials.Key;
string signature = CryptoUtility.ComputeHmac256(accountKey.KeyValue, message);
if (!string.IsNullOrEmpty(accountKey.KeyName))
{
request.Headers.Add(Constants.HeaderConstants.KeyNameHeader, accountKey.KeyName);
}
request.Headers.Add(
"Authorization",
string.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}", this.canonicalizer.AuthorizationScheme, this.credentials.AccountName, signature));
}
}
开发者ID:jianghaolu,项目名称:azure-storage-net,代码行数:33,代码来源:SharedKeyAuthenticationHandler.cs
示例6: Create
public string Create(string url)
{
try
{
// setup web request to tinyurl
request = (HttpWebRequest)WebRequest.Create(string.Format(TINYURL_ADDRESS_TEMPLATE, url));
request.Timeout = REQUEST_TIMEOUT;
request.UserAgent = USER_AGENT;
// get response
response = (HttpWebResponse)request.GetResponse();
// prase response stream to string
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(ENCODING_NAME));
// convert the buffer into string and store in content
StringBuilder sb = new StringBuilder();
while (reader.Peek() >= 0)
{
sb.Append(reader.ReadLine());
}
return sb.ToString();
}
catch (Exception)
{
return null;
}
}
开发者ID:TlhanGhun,项目名称:digiTweetSnarlEdition,代码行数:29,代码来源:TinyUrlClient.cs
示例7: CloudFilesRequest
/// <summary>
/// Constructor with proxy credentials provided
/// </summary>
/// <param name="request">The request being sent to the server</param>
/// <param name="proxyCredentials">Proxy credentials</param>
/// <exception cref="System.ArgumentNullException">Thrown when any of the reference arguments are null</exception>
public CloudFilesRequest(HttpWebRequest request, ProxyCredentials proxyCredentials)
{
if (request == null) throw new ArgumentNullException();
_httpWebRequest = request;
_proxyCredentials = proxyCredentials;
}
开发者ID:asw,项目名称:csharp-cloudfiles,代码行数:13,代码来源:CloudFilesRequest.cs
示例8: CopyHeaders
public static void CopyHeaders(HttpWebRequest src, HttpWebRequest dest)
{
foreach (string header in src.Headers)
{
var values = src.Headers.GetValues(header);
if (values == null)
continue;
if (WebHeaderCollection.IsRestricted(header))
{
switch (header)
{
case "Accept":
dest.Accept = src.Accept;
break;
case "Connection":
// explicitly ignoring this
break;
case "Content-Length":
break;
case "Content-Type":
dest.ContentType = src.ContentType;
break;
case "Date":
break;
case "Expect":
// explicitly ignoring this
break;
case "Host":
dest.Host = src.Host;
break;
case "If-Modified-Since":
dest.IfModifiedSince = src.IfModifiedSince;
break;
case "Range":
throw new NotSupportedException("Range copying isn't supported at this stage, we don't support range queries anyway, so it shouldn't matter");
case "Referer":
dest.Referer = src.Referer;
break;
case "Transfer-Encoding":
dest.SendChunked = src.SendChunked;
break;
case "User-Agent":
dest.UserAgent = src.UserAgent;
break;
case "Proxy-Connection":
dest.Proxy = src.Proxy;
break;
default:
throw new ArgumentException(string.Format("No idea how to handle restricted header: '{0}'", header));
}
}
else
{
foreach (var value in values)
{
dest.Headers[header] = value;
}
}
}
}
开发者ID:cocytus,项目名称:ravendb,代码行数:60,代码来源:HttpRequestHelper.cs
示例9: Download
public static void Download()
{
using (WebClient wcDownload = new WebClient())
{
try
{
webRequest = (HttpWebRequest)WebRequest.Create(optionDownloadURL);
webRequest.Credentials = CredentialCache.DefaultCredentials;
webResponse = (HttpWebResponse)webRequest.GetResponse();
Int64 fileSize = webResponse.ContentLength;
strResponse = wcDownload.OpenRead(optionDownloadURL);
strLocal = new FileStream(optionDownloadPath, FileMode.Create, FileAccess.Write, FileShare.None);
int bytesSize = 0;
byte[] downBuffer = new byte[2048];
downloadForm.Refresh();
while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
strLocal.Write(downBuffer, 0, bytesSize);
PercentProgress = Convert.ToInt32((strLocal.Length * 100) / fileSize);
pBar.Value = PercentProgress;
pLabel.Text = "Downloaded " + strLocal.Length + " out of " + fileSize + " (" + PercentProgress + "%)";
downloadForm.Refresh();
}
}
catch { }
finally
{
webResponse.Close();
strResponse.Close();
strLocal.Close();
extractAndCleanup();
downloadForm.Hide();
}
}
}
开发者ID:bodiroga,项目名称:Avalon,代码行数:35,代码来源:checkForUpdate.cs
示例10: CouchRequest
/// <summary>
/// Basic Authorization Header
/// </summary>
/// <param name="uri"></param>
/// <param name="username"></param>
/// <param name="password"></param>
public CouchRequest(string uri, string username, string password)
{
request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Clear(); //important
// Deal with Authorization Header
if (username != null)
{
string authValue = "Basic ";
string userNAndPassword = username + ":" + password;
// Base64 encode
string b64 = System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(userNAndPassword));
authValue = authValue + b64;
request.Headers.Add("Authorization", authValue);
}
request.Headers.Add("Accept-Charset", "utf-8");
request.Headers.Add("Accept-Language", "en-us");
request.ContentType = "application/json";
request.KeepAlive = true;
request.Timeout = 10000;
}
开发者ID:Rychard,项目名称:LoveSeat,代码行数:31,代码来源:CouchRequest.cs
示例11: GerarArquivo
public static string GerarArquivo(string texto)
{
Uri url = new Uri(string.Concat(URL_TTS_GOOGLE, texto));
_request = (HttpWebRequest)HttpWebRequest.Create(url);
_request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
_request.UseDefaultCredentials = true;
if (!string.IsNullOrEmpty(ProxyPath))
{
_request.Proxy = WebRequest.GetSystemWebProxy();
_request.Proxy.Credentials = new NetworkCredential(ProxyUserName, ProxyPassword, ProxyDomain);
}
WebResponse response = _request.GetResponse();
Stream fileContent = response.GetResponseStream();
caminhoTemp = Path.ChangeExtension(Path.GetTempFileName(), ".mp3");
using (Stream file = File.OpenWrite(caminhoTemp))
{
CopyStream(fileContent, file);
file.Flush();
file.Close();
}
fileContent.Close();
fileContent.Dispose();
return caminhoTemp;
}
开发者ID:rcarubbi,项目名称:Google.TTS,代码行数:30,代码来源:TTSHelper.cs
示例12: UpdateCookies
protected void UpdateCookies(string jScriptBody, HttpWebRequest request)
{
int setCookieIndex = -1;
while ((setCookieIndex = jScriptBody.IndexOf("setCookie('")) != -1)
{
jScriptBody = jScriptBody.Substring(setCookieIndex + 11);
string cookieName = jScriptBody.GetParent("'");
string cookieValue = jScriptBody.GetChild(",", ',').Trim();
if (!cookieValue.StartsWith("'"))
{
switch (cookieValue)
{
case "document.referrer":
cookieValue = request.Referer;
break;
}
}
else cookieValue = cookieValue.GetChild("'", '\'');
if (cookieValue != null)
cookieValue = Uri.EscapeDataString(cookieValue);
string cookieObject =
(cookieName + "=" + cookieValue);
Cookies.SetCookies(request.RequestUri, cookieObject);
}
}
开发者ID:SirJamal,项目名称:Sulakore,代码行数:29,代码来源:HRequest.cs
示例13: GetConnection
public WebConnection GetConnection (HttpWebRequest request)
{
WebConnection cnc = null;
lock (connections) {
WeakReference cncRef = null;
// Remove disposed connections
int end = connections.Count;
ArrayList removed = null;
for (int i = 0; i < end; i++) {
cncRef = (WeakReference) connections [i];
cnc = cncRef.Target as WebConnection;
if (cnc == null) {
if (removed == null)
removed = new ArrayList (1);
removed.Add (i);
}
}
if (removed != null) {
for (int i = removed.Count - 1; i >= 0; i--)
connections.RemoveAt ((int) removed [i]);
}
cnc = CreateOrReuseConnection (request);
}
return cnc;
}
开发者ID:GirlD,项目名称:mono,代码行数:30,代码来源:WebConnectionGroup.cs
示例14: GetHttpWebResp
public virtual HttpWebResponse GetHttpWebResp(HttpWebRequest webReq)
{
var countTry = 20;
var repeat = true;
HttpWebResponse res = null;
while (repeat && countTry > 0)
try
{
res = (HttpWebResponse)webReq.GetResponse();
repeat = false;
}
catch (WebException wex)
{
countTry--;
File.AppendAllText("log.txt", wex.Message + Environment.NewLine);
File.AppendAllText("log.txt", "++" + Environment.NewLine);
File.AppendAllText("log.txt", wex.Status.ToString() + Environment.NewLine);
File.AppendAllText("log.txt", "++" + Environment.NewLine);
File.AppendAllText("log.txt", "GetHttpWebResp" + Environment.NewLine);
File.AppendAllText("log.txt", "------" + Environment.NewLine);
webReq = GetHttpWebReq(url);
}
return res;
}
开发者ID:ruslanruslanruslan,项目名称:Parser,代码行数:25,代码来源:WebClAlwaysNewProxy.cs
示例15: SendRequest
public void SendRequest(HttpWebRequest request)
{
int index = 0, size = 0;
byte[][] data = new byte[Count * 2][];
foreach (string key in AllKeys)
{
data[index] = HttpUtility.UrlEncodeToBytes(key);
size += data[index++].Length;
data[index] = HttpUtility.UrlEncodeToBytes(this[key]);
size += data[index++].Length;
}
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = size + Count * 2 - 1;
using (Stream requestStream = request.GetRequestStream())
{
for (int i = 0; i < data.Length; i++)
{
byte[] buff = data[i];
requestStream.Write(buff, 0, buff.Length);
if (i < data.Length - 1)
requestStream.WriteByte(SeparatorBytes[i % 2]);
}
}
}
开发者ID:kidaa,项目名称:Pulse,代码行数:27,代码来源:HttpRequestParams.cs
示例16: DisposeObject
private static void DisposeObject(ref HttpWebRequest request, ref HttpWebResponse response,
ref Stream responseStream, ref StreamReader reader)
{
if (request != null)
{
request = null;
}
if (response != null)
{
response.Close();
response = null;
}
if (responseStream != null)
{
responseStream.Close();
responseStream.Dispose();
responseStream = null;
}
if (reader != null)
{
reader.Close();
reader.Dispose();
reader = null;
}
}
开发者ID:superhappy123,项目名称:Test,代码行数:25,代码来源:WebUrlRead.cs
示例17: NonEntityOperationResult
internal NonEntityOperationResult(object source, HttpWebRequest request, AsyncCallback callback, object state)
{
this.source = source;
this.request = request;
this.userCallback = callback;
this.userState = state;
}
开发者ID:modulexcite,项目名称:SilverlightWpfContrib,代码行数:7,代码来源:NonEntityOperationResult.cs
示例18: RequestAndRespond
private Result RequestAndRespond(HttpWebRequest request, string content)
{
HttpStatusCode statusCode = HttpStatusCode.NotFound;
try
{
var contentBytes = Encoding.UTF8.GetBytes(content);
request.ContentLength = contentBytes.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(contentBytes, 0, contentBytes.Length);
}
using (var response = request.GetResponse() as HttpWebResponse)
{
statusCode = HttpClient.GetStatusCode(response);
}
}
catch (WebException webException)
{
var response = webException.Response as HttpWebResponse;
statusCode = HttpClient.GetStatusCode(response);
}
return HttpStatusCodeExtensions.ToResult(statusCode);
}
开发者ID:B2MSolutions,项目名称:reyna.net,代码行数:26,代码来源:HttpClient.cs
示例19: ProcessHttpWebRequest
protected override void ProcessHttpWebRequest(HttpWebRequest httpWebRequest)
{
if (this.ReadWriteTimeout.HasValue)
{
httpWebRequest.ReadWriteTimeout = (int)this.ReadWriteTimeout.Value.TotalMilliseconds;
}
}
开发者ID:razaraz,项目名称:Pscx,代码行数:7,代码来源:HttpResourceContentCommandBase.cs
示例20: GetResponse
public static HttpWebResponse GetResponse(HttpWebRequest request)
{
Contract.Requires(request != null);
Debug.WriteLine("Request: " + request.RequestUri);
var response = request.GetResponse() as HttpWebResponse;
return response;
}
开发者ID:nozzy83,项目名称:evelib,代码行数:7,代码来源:HttpRequestHelper.cs
注:本文中的System.Net.HttpWebRequest类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论