2

我尝试在我的网站上使用 Facebook 帐户登录,但应用程序给了我错误,远程服务器返回错误:(400)错误请求。

下面是我的代码:

public string WebRequest(Method method, string url, string postData)
{

    HttpWebRequest webRequest = null;
    StreamWriter requestWriter = null;
    string responseData = "";    

    webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
    webRequest.Method = method.ToString();
    webRequest.ServicePoint.Expect100Continue = false;
    webRequest.UserAgent = "[You user agent]";
    webRequest.Timeout = 50000;


    if (method == Method.POST)
    {
        webRequest.ContentType = "application/x-www-form-urlencoded";

        //POST the data.
        requestWriter = new StreamWriter(webRequest.GetRequestStream());

        try
        {
            requestWriter.Write(postData);
        }
        catch
        {
            throw;
        }

        finally
        {
            requestWriter.Close();
            requestWriter = null;
        }
    }

    responseData = WebResponseGet(webRequest);
    webRequest = null;
    return responseData;
}

*它给了我这种方法的错误: *

 public string WebResponseGet(HttpWebRequest webRequest)
{
    StreamReader responseReader = null;
    string responseData = "";

    try
    {
        responseReader = new      StreamReader(webRequest.GetResponse().GetResponseStream());
        responseData = responseReader.ReadToEnd();
    }
    catch
    {
        throw;
    }
    finally
    {
        webRequest.GetResponse().GetResponseStream().Close();
        responseReader.Close();
        responseReader = null;
    }

    return responseData;
}
4

1 回答 1

1

自从我玩过 webRequest 以来已经有一段时间了,但我认为你的问题可能是

webRequest.GetResponse().GetResponseStream().Close(); 

在 finally 块中。既然你已经打过电话

webRequest.GetResponse().GetResponseStream()

在 try 块的主体中​​。文档指出:

GetResponse 方法向 Internet 资源发送请求并返回 WebResponse 实例。如果请求已通过调用 GetRequestStream 发起,则 GetResponse 方法完成请求并返回任何响应。

因此,当我阅读它时,响应已经在 try 块中返回,然后当您在 finally 块中再次调用它时,它失败了......因为它已经被检索到了。只需注释掉那条线,看看你是怎么走的。当您关闭 StreamReader 时,它应该关闭底层连接。

所以试试:

public string WebResponseGet(HttpWebRequest webRequest)
{
    StreamReader responseReader = null;
    string responseData = "";

    try
    {
        responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
        responseData = responseReader.ReadToEnd();
    }
    catch
    {
        throw;
    }
    finally
    {
        responseReader.Close();
    }

    return responseData;
}
于 2013-09-05T03:51:39.837 回答