标签: webrequest

C#:使用超时下载URL

在.NET中最好的方法是什么?我总是忘记我需要Dispose()(或包裹using).

编辑:经过长时间的使用WebRequest,我发现了自定义WebClient.好多了.

c# timeout .net-3.0 webrequest httpwebrequest

6
推荐指数
3
解决办法
2万
查看次数

复制Http Request InputStream

我正在实现一个代理操作方法,该方法转发传入的Web请求并将其转发到另一个网页,添加一些标头.动作方法为GET请求工作文件,但我仍然在努力转发传入的POST请求.

问题是我不知道如何正确地将请求主体写入传出的HTTP请求流.

这是我到目前为止的缩短版本:

//the incoming request stream
var requestStream=HttpContext.Current.Request.InputStream;
//the outgoing web request
var webRequest = (HttpWebRequest)WebRequest.Create(url);
...

//copy incoming request body to outgoing request
if (requestStream != null && requestStream.Length>0)
            {
                long length = requestStream.Length;
                webRequest.ContentLength = length;
                requestStream.CopyTo(webRequest.GetRequestStream())                    
            }

//THE NEXT LINE THROWS A ProtocolViolationException
 using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
                {
                    ...
                }
Run Code Online (Sandbox Code Playgroud)

一旦我在传出的http请求上调用GetResponse,我就会收到以下异常:

ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会发生这种情况,因为requestStream.CopyTo应该负责编写正确数量的字节.

任何建议将不胜感激.

谢谢,

阿德里安

c# asp.net asp.net-mvc webrequest httpwebrequest

6
推荐指数
1
解决办法
2万
查看次数

WebException.Response.GetResponseStream()限制为65536个字符

我正在尝试使用HttpWebRequest和HttpWebResponse从网页中检索HTML代码.

response = (HttpWebResponse)request.GetResponse();
...
Stream stream = response.GetResponseStream();
Run Code Online (Sandbox Code Playgroud)

响应对象的ContentLength值为106142.当我查看流对象时,它的长度为65536.使用ReadToEnd()使用StreamReader读取流时,仅返回前65536个字符.

我怎样才能获得整个代码?

编辑:

使用以下代码段:

catch (WebException ex)
{
    errorMessage = errorMessage + ex.Message;
    if (ex.Response != null) {
        if (ex.Response.ContentLength > 0) 
        {
            using (Stream stream = ex.Response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string pageOutput = reader.ReadToEnd().Trim();
Run Code Online (Sandbox Code Playgroud)

ex.Response.ContentLength = 106142

ex.Response.GetResponseStream().长度= 65536

stream.Length = 65536

pageOutput.Length = 65534(由于修剪)

是的,代码实际上是截断的.

.net c# webrequest

6
推荐指数
2
解决办法
4300
查看次数

阅读RoR中的参数数组

如果我有以下URL:

http://test.com?x=1&x=2&x=3&x=4&x=5&x=6&x=7
Run Code Online (Sandbox Code Playgroud)

那么我怎样才能读出所有"x"值?

添加了新评论:感谢您的所有答案.我基本上来自Java和.Net背景,最近开始寻找Ruby和Rails.就像在Java中一样,我们没有像request.getParameterValues("x")那样的东西;

ruby ruby-on-rails webrequest

6
推荐指数
2
解决办法
5973
查看次数

使用Google Chrome webRequest API进行简单转发

我正在尝试创建Chrome扩展程序,以帮助我了解Chrome的webRequest API,方法是复制使用此答案所做的操作,但不使用命名空间的实验部分,因为webRequest现在位于Chrome的主干中,所以不再需要.

在我的后台页面中,我有代码:

<!DOCTYPE html>
<html>
  <head>
  <script>
function interceptRequest(request) {
    return { redirectUrl: 'http://www.yahoo.com' }
}
chrome.webRequest.onBeforeRequest.addListener(interceptRequest, { urls: ['*://*.google.com/*'] }, ['blocking']);
  </script>
  </head><body></body>
</html>
Run Code Online (Sandbox Code Playgroud)

在我的清单文件中,我有:

{
  "name": "My Extension",
  "version": "0.1",
  "background_page": "background.html",
  "permissions" : [
     "webRequest",
     "webRequestBlocking",
     "*://*/*"
  ]
}
Run Code Online (Sandbox Code Playgroud)

根据之前提出的问题,当我访问https://www.google.com并加载我的扩展程序时,我应该转发到http://www.yahoo.com,但是,https://www.google.com加载没有任何转发效果.为了简单地使用Chrome中的webRequest API将用户从一个URI转发到另一个URI,我需要做什么?

google-chrome forwarding webrequest google-chrome-extension

6
推荐指数
1
解决办法
3830
查看次数

登录会话未使用WebRequest/Response转移到新网页?

好吧,我已经在这个独奏上绞尽脑汁待了太久.即使花了很多时间在这个和许多其他网站上,我也无法破解它.

基本上,我试图使用WebRequest/Response从LogIn页面后面的网页中删除一些数据. (我已经使用WebBrowser控件执行此操作,其中一些分层事件导航到不同的网页,但在尝试重构时会导致一些问题 - 更不用说已经声明使用隐藏的表单来完成工作是'坏的实践'.)

这就是我所拥有的:

        string formParams = string.Format("j_username={0}&j_password={1}", userName, userPass);
        string cookieHeader;

        WebRequest request = WebRequest.Create(_signInPage);
        request.ContentType = "text/plain";
        request.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(formParams);
        request.ContentLength = bytes.Length;
        using (Stream os = request.GetRequestStream())
        {
            os.Write(bytes, 0, bytes.Length);
        }
        WebResponse response = request.GetResponse();
        cookieHeader = response.Headers["Set-Cookie"];

        WebRequest getRequest = WebRequest.Create(sessionHistoryPage);
        getRequest.Method = "GET";
        getRequest.Headers.Add("Cookie", cookieHeader);
        WebResponse getResponse = getRequest.GetResponse();
        try
        {
            using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
            {
                textBox1.AppendText(sr.ReadToEnd());
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            throw;
        } …
Run Code Online (Sandbox Code Playgroud)

.net c# forms-authentication webrequest

6
推荐指数
1
解决办法
2946
查看次数

如何在.net上为WebClient设置TimeOut?

我下载了一些文件,但我也想为webclient设置超时.我看到没有变化只是我们可以使用重写WebRequest.我已经做了但它不起作用.我的意思是重写GetWebRequest方法不起作用..这是我的代码

  public class VideoDownloader : Downloader
{
    /// <summary>
    /// Initializes a new instance of the <see cref="VideoDownloader"/> class.
    /// </summary>
    /// <param name="video">The video to download.</param>
    /// <param name="savePath">The path to save the video.</param>
    public VideoDownloader(VideoInfo video, string savePath)
        : base(video, savePath)
    { }


    /// <summary>
    /// Starts the video download.
    /// </summary>
    public override void Execute()
    {
        // We need a handle to keep the method synchronously
        var handle = new ManualResetEvent(false);

        var client = new WebClient();


        client.DownloadFileCompleted …
Run Code Online (Sandbox Code Playgroud)

c# timeout webclient webrequest downloadfileasync

6
推荐指数
1
解决办法
1万
查看次数

WebRequest.Create抛出IOException"指定的注册表项不存在."

我正在调用这行代码来访问azure服务器:

var request = (HttpWebRequest)WebRequest.Create(uri);
Run Code Online (Sandbox Code Playgroud)

并收到此例外.有人知道怎么用它来管理吗?

mscorlib.dll!Microsoft.Win32.RegistryKey.Win32Error(int errorCode, string str) + 0x189 bytes    
mscorlib.dll!Microsoft.Win32.RegistryKey.GetValueKind(string name) + 0x7f bytes 
System.dll!System.Net.HybridWebProxyFinder.InitializeFallbackSettings() + 0xb8 bytes    
System.dll!System.Net.HybridWebProxyFinder.HybridWebProxyFinder() + 0x1e bytes  
[Native to Managed Transition]  
[Managed to Native Transition]  
System.dll!System.Net.HybridWebProxyFinder.HybridWebProxyFinder(System.Net.AutoWebProxyScriptEngine engine) + 0x37 bytes    
System.dll!System.Net.AutoWebProxyScriptEngine.AutoWebProxyScriptEngine(System.Net.WebProxy proxy, bool useRegistry) + 0x190 bytes  
System.dll!System.Net.WebProxy.UnsafeUpdateFromRegistry() + 0x67 bytes  
System.dll!System.Net.WebProxy.WebProxy(bool enableAutoproxy) + 0x44 bytes  
System.dll!System.Net.Configuration.DefaultProxySectionInternal.DefaultProxySectionInternal(System.Net.Configuration.DefaultProxySection section) + 0x3d9 bytes 
System.dll!System.Net.Configuration.DefaultProxySectionInternal.GetSection() + 0xbe bytes   
System.dll!System.Net.WebRequest.InternalDefaultWebProxy.get() + 0x7e bytes 
System.dll!System.Net.HttpWebRequest.HttpWebRequest(System.Uri uri, System.Net.ServicePoint servicePoint) + 0x18d bytes 
System.dll!System.Net.HttpRequestCreator.Create(System.Uri Uri) + 0x50 bytes …
Run Code Online (Sandbox Code Playgroud)

.net c# registry webrequest ioexception

6
推荐指数
1
解决办法
6377
查看次数

参数HTTP Post c#

我正在制作一个HTTP POST方法来获取数据.我有一个想法是创建一个方法来获取一个特定的参数,但是当我不知道获取参数时.在HTTP GET中,参数位于URL中,并且更容易获取参数.如何创建一个方法来获取HTTP Post中的所有数据?在PHP中,例如当您显示var $ _POST时,您将显示正文帖子中的所有数据.我怎么能在C#中做到这一点?

我的方法是这样的:

[HttpPost]
[AllowAnonymous]
public IHttpActionResult Test()
{
// Get URL Args for example is 
var args = Request.RequestUri.Query;
// But if the arguments are in the body i don't have idea.
}
Run Code Online (Sandbox Code Playgroud)

c# http webrequest http-post httpwebrequest

6
推荐指数
1
解决办法
920
查看次数

如何用HttpClient替换WebClient?

我的asp.net mvc Web应用程序中有以下WebClient:

using (WebClient wc = new WebClient()) // call the Third Party API to get the account id 
{
     string url = currentURL + "resources/" + ResourceID + "/accounts?AUTHTOKEN=" + pmtoken;
     var json = await wc.DownloadStringTaskAsync(url);
 }
Run Code Online (Sandbox Code Playgroud)

那么有人可以建议我如何将它从WebClient更改为HttpClient?

.net webclient webrequest webclient-download

6
推荐指数
1
解决办法
8447
查看次数