HttpWebRequest only works while fiddler is running

和自甴很熟 提交于 2019-12-23 01:54:28

问题


I'm having some issues with the following code. It'll run fine when Fiddler is on, but it times out when Fiddler isn't running.

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();

Hope you guys have an answer. (I read another thread on SO, but I none of the answers worked for me)

Thanks!


回答1:


Try using this to read the response stream:

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

[Edit] I just saw that you ultimatley wanted a string from the response, so use this to convert the byte array to a string:

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


来源:https://stackoverflow.com/questions/12485310/httpwebrequest-only-works-while-fiddler-is-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!