标签: httpwebresponse

在c#中使用windows应用程序执行http方法

有许多站点在表单提交时调用脚本并使用HTTP POST或GET传递参数,使用Web调试器我已经找到了传递的参数.现在我希望通过我在C#中的Windows应用程序做同样的事情.我怎样才能实现这样的功能?

我目前在C#中使用HttpWebRequest和HttpWebResponse类.但这是一个痛苦,因为我必须为我尝试加载和工作的每个页面编写显式代码.例如,我正在尝试将用户名和密码传递到php页面并获取响应,该响应将发送cookie和页面作为回报,基于此我确定用户是否已登录.

HttpWebRequest loginreq = createreq("http://www.indyarocks.com/mobile/index.php");
                String logintext = "username=" + TxtUsrname.Text + "&pass=" + TxtPasswd.Password + "&button.x=0&button.y=0";
                loginreq.ContentLength = logintext.Length;
                StreamWriter writerequest = new StreamWriter(loginreq.GetRequestStream());
                writerequest.Write(logintext);
                writerequest.Close();
                HttpWebResponse getloginpageresponse = (HttpWebResponse)loginreq.GetResponse();
                cookie = getloginpageresponse.Cookies[0];
                BinaryFormatter bf1 = new BinaryFormatter();
                Stream f1 = new FileStream("E:\\cookie.dat", FileMode.OpenOrCreate);
                bf1.Serialize(f1, cookie);
                f1.Close();

                string nexturl = getloginpageresponse.Headers[HttpResponseHeader.Location];
                StreamReader readresponse = new StreamReader(getloginpageresponse.GetResponseStream());
                if (nexturl == "p_mprofile.php")
                {
                    MessageBox.Show("Login Successful");
                    GrpMsg.IsEnabled = true;
                }
                else if (nexturl == "index.php?msg=1")
                {
                    MessageBox.Show("Invalid Credentials Login again"); …
Run Code Online (Sandbox Code Playgroud)

c# windows httpwebrequest httpwebresponse

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

了解异步HttpWebRequest

我试图弄清楚它是如何工作的.

HttpWebRequest有一个BeginGetResponse接受参数a的方法ResponseCallback.首先,这个回调是立即调用(在新线程中)还是从服务器收到响应?或者是EndGetResponse等待响应的工作?

其次,一旦你有了响应,就可以立即访问响应流,但是在完成下载之前,流不包含整个页面,因此BeginRead.但是,我似乎能够通过像这样的属性立即访问所有标题HttpWebResponse.ContentLength.这是否意味着EndGetResponse在标题完全下载之前不会完成,或者是在调用ContentLength参数时它会挂起一点直到收到标题?

c# asynchronous httpwebrequest httpwebresponse

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

编码来自HttpWebRequest的内容的问题

我使用HttpWebRequest使用以下代码读取网页:

 var pageurl = new Uri(url, UriKind.Absolute);

        var request = (HttpWebRequest)WebRequest.Create(pageurl);
        request.Method = "GET";
        request.AutomaticDecompression = DecompressionMethods.GZip;
        request.KeepAlive = false;
        request.ConnectionGroupName = Guid.NewGuid().ToString();
        request.ServicePoint.Expect100Continue = false;
        request.Pipelined = false;
        request.MaximumResponseHeadersLength = 4;

        if (ignoreCertificateErrors)
        {
            ServicePointManager.ServerCertificateValidationCallback += AcceptAllCertificatePolicy;
        }

        var response = (HttpWebResponse)request.GetResponse();


    if (response != null)
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                return reader.ReadToEnd();
            }
        }
Run Code Online (Sandbox Code Playgroud)

当传递的语言是英语时,这种方法非常有效,但当其他语言如西班牙语时,我会在返回的内容中获得大量的 .

代码是否有问题,或者是否存在我缺少的编码方式?

c# asp.net webrequest httpwebrequest httpwebresponse

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

如何在服务器响应上编写文件对象而不在服务器上保存文件?

我正在使用带DWR的Spring.我想返回一个文件对象作为响应,但是我将文件(待发送)保存在服务器临时位置,然后将其位置作为href发送到客户端的锚标记,但是我想知道是否有办法抛出直接在浏览器上写入响应对象而不将其临时保存在服务器上.

我期望是否可以通过DWR将文件作为响应发送.

java spring dwr response.write httpwebresponse

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

如何使用自定义WebResponse创建WebException

我使用MVC4 Web API创建了一个RESTful Web服务.如果出现问题,我会抛出WebException.

throw new WebException("Account not found");
Run Code Online (Sandbox Code Playgroud)

这是处理异常的客户端代码:

private void webClientPost_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        try
        {
            if (e.Error == null)
            {
                // Display result
                textBoxResult.Text = e.Result;
            }
            else
            {
                // Display status code
                if (e.Error is WebException)
                {
                    StringBuilder displayMessage = new StringBuilder();

                    WebException we = (WebException)e.Error;
                    HttpWebResponse webResponse = (System.Net.HttpWebResponse)we.Response;

                    displayMessage.AppendLine(webResponse.StatusDescription);

                    // Gets the stream associated with the response.
                    Stream receiveStream = webResponse.GetResponseStream();
                    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

                    // Pipes the stream to a higher level …
Run Code Online (Sandbox Code Playgroud)

.net httpwebresponse system.net.webexception asp.net-mvc-4 asp.net-web-api

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

当文件太大时,C#HttpWebResponse contentlength = -1

我从烂番茄网站获得了json格式的字符串.我的代码看起来像

HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";

HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

using(StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    //Code I'm using the reader with
}
Run Code Online (Sandbox Code Playgroud)

当我运行一个返回1-4电影的电影搜索时它工作正常.但是,如果我尝试获得5或更多的结果,它将无法正常工作.webResponse内容长度为-1.当我返回4部电影的结果时,内容长度为7,449.

c# httpwebrequest httpwebresponse

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

WebException Response属性返回null

我正在扫描一个有很多路径示例的网址:http://url.com/path11000.有时我会得到一个WebException但是在我的catch块中,NullReferenceException如果我不使用该行,它将引发错误
if (x.Status == WebExceptionStatus.ProtocolError && x.Response != null)

所以我的问题是:下面的代码是修复错误还是忽略它?

错误没有特定的错误路径只是随机像http://url.com/path10或任何其他链接谢谢:)

catch (WebException x)
{
    if (x.Status == WebExceptionStatus.ProtocolError && x.Response != null)
    {
        HttpWebResponse response = (HttpWebResponse)x.Response;
        if (response.StatusCode == HttpStatusCode.NotFound)
        {
           listBox3.Items.add(listBox1.Items[i].ToString());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# error-handling httpwebresponse

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

DownloadString和HttpWebResponse没有返回完整的JSON内容

我试图在字符串中存储来自以下url的JSON响应.大多数情况下,我运行代码,JSON响应的最后几个字符被切断.当您在浏览器中访问该URL时,将显示完整的JSON响应.有时我的代码有效,但大多数情况下它返回部分内容.

如果我减少了我请求的网址中查询的长度,我会收到更多内容,更接近完整响应,这很奇怪.如果我完全删除查询字符串,通常会返回完整的JSON响应.问题是我想保持查询字符串不变.

我尝试了各种替代方法,包括更改编码,使用HttpWebRequest/HttpWebResponse,将响应复制到MemoryStream,使用字节缓冲区读取响应,更改协议版本等.

关于如何获得完整响应并能解释发生了什么的任何想法?谢谢!

System.Net.WebClient wc = new System.Net.WebClient();            
string data = wc.DownloadString("http://static.arcgis.com/attribution/World_Topo_Map?f=json&callback=dojo.io.script.jsonp_dojoIoScript19._jsonpCallback");
Console.Write(data);// String should end with ",-119.2]}]}]});"
Console.Read();
Run Code Online (Sandbox Code Playgroud)

.net c# webclient httpwebrequest httpwebresponse

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

如何忽略/跳过/处理 HttpWebResponse 错误并仍将 JSON 返回到我的代码?

我正在尝试通过 C# 及其 API 设置对 Stripe 的调用。我正在使用以下代码通过帖子向他们的 API 添加新卡,并使用 JSON 响应来确定下一步

(我试图去掉所有不必要的东西)

public static string stripeAPIcall(string customerId, string parameters, string stripeApiKey) {
    using (var stripeAPI = new System.Net.WebClient())
    {
      try
      {
        // set credentials
        stripeAPI.Credentials = new System.Net.NetworkCredential(stripeApiKey, "");

        //Set Headers
        stripeAPI.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
        stripeAPI.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

        return stripeAPI.UploadString("https://api.stripe.com/v1/customers/" + customerId + "/cards, parameters);
    }
    catch (WebException ex)
    {   
        return "error";
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当成功时,这可以很好地创建卡片。但是,如果出现错误,例如

我使用了条纹“card_declined”测试卡号 4000000000000002

结果是具有以下 JSON 结构的 402 错误 …

c# asp.net api json httpwebresponse

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

如何使用 proxy.ModifyResponse?

我已经实现了最基本的反向代理来拉一个页面,然后向正文添加一些内容。不幸的是,我添加到 html 的尝试没有生效。下面的代码只显示了原始页面,但没有我在响应中添加的“猴子”。需要哪些额外的调用才能使其工作?我最终想用它来替换自定义 css 的 css。

package main

import (
    "log"
    "net/http"
    "net/http/httputil"
    "net/url"
    "fmt"
    "github.com/PuerkitoBio/goquery"
    "bytes"
)

type Director func(*http.Request)

func (f Director) Then(g Director) Director {
    return func(req *http.Request) {
        f(req)
        g(req)
    }
}

func hostDirector(host string) Director {
    return func(req *http.Request) {
        req.Host = host
    }
}

func UpdateResponse(r *http.Response) error {
    doc, err := goquery.NewDocumentFromReader(r.Body)
    if err != nil{
        //log.New("Research")
        log.Fatal("Bad doc %v", err)
        return err
    }
    html, err := goquery.OuterHtml(doc.First())
    if err != nil{
        log.Fatal("Bad …
Run Code Online (Sandbox Code Playgroud)

reverse-proxy httpwebresponse go

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