2

我对以下代码有一些问题。当 Fiddler 打开时它会运行良好,但是当 Fiddler 不运行时它会超时。

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 上阅读了另一个帖子,但没有一个答案对我有用)

谢谢!

4

1 回答 1

0

尝试使用它来读取响应流:

    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;
    }

[编辑] 我刚刚看到你最终想要一个来自响应的字符串,所以使用它来将字节数组转换为字符串:

/// <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);
}
于 2012-09-18T21:32:36.207 回答