HttpWebRequest的唯一而小提琴手正在运行的工作原理(HttpWebRequest onl

2019-09-22 13:58发布

我在用下面的代码的一些问题。 当小提琴手是它会运行良好,但它超时时提琴手没有运行。

IWebProxy proxy = websiterequester.Proxy;
websiterequester = (HttpWebRequest)WebRequest.Create("http://website.com/");
websiterequester.CookieContainer = cookieJar;
websiterequester.Method = "GET";
websiterequester.Referer = "http://website.com/";
if (websiterequester.Proxy != null)
{
  websiterequester.Proxy = null;
}

try
{
  objStream1 = websiterequester.GetResponse().GetResponseStream();
}
catch (WebException ex)
{
  return "oops";
}

objReader1 = new StreamReader(objStream1);
string thiscamebacks = objReader1.ReadToEnd();

希望你们有一个答案。 (我读了SO另一个线程,但我没有答案的工作对我来说)

谢谢!

Answer 1:

尝试使用此功能读取响应流:

    private byte[] ReadWebResponse(WebResponse response)
    {
        byte[] bytes = null;
        if(response == null) return null;

        using(Stream responseStream = response.GetResponseStream())
        {
            using(BinaryReader readStream = new BinaryReader(responseStream))
            {
                using(MemoryStream memoryStream = new MemoryStream())
                {
                    byte[] buffer = new byte[256];
                    int count;
                    int totalBytes = 0;
                    while((count = readStream.Read(buffer, 0, 256)) > 0)
                    {
                        memoryStream.Write(buffer, 0, count);
                        totalBytes += count;
                    }
                    memoryStream.Position = 0;
                    bytes = new byte[totalBytes];
                    memoryStream.Read(bytes, 0, totalBytes);
                }
            }
        }
        return bytes;
    }

[编辑]我刚才看到你ultimatley想从响应字符串,所以用这个字节数组转换为字符串:

/// <summary>
/// Returns the byte array as a string, or null
/// </summary>
public static string GetByteString(byte[] b)
{
    if (b == null) return null;
    return Encoding.UTF8.GetString(b);
}


文章来源: HttpWebRequest only works while fiddler is running