本文整理汇总了C#中System.Net.HttpWebRequest类的典型用法代码示例。如果您正苦于以下问题:C# HttpWebRequest类的具体用法?C# HttpWebRequest怎么用?C# HttpWebRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpWebRequest类属于System.Net命名空间,在下文中一共展示了HttpWebRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InsertSoapEnvelopeIntoWebRequest
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
示例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;
}
示例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;
}
示例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;
}
示例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));
}
}
示例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;
}
}
示例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;
}
示例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;
}
}
}
}
示例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();
}
}
}
示例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;
}
示例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;
}
示例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);
}
}
示例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;
}
示例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;
}
示例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]);
}
}
}