简体   繁体   English

使用HttpWebRequest.GetResponse时出现KeepAliveException

[英]KeepAliveException when using HttpWebRequest.GetResponse

I am trying to POST an attachment to CouchDB using the HttpWebRequest. 我正在尝试使用HttpWebRequest将附件发布到CouchDB。 However, when I attempt "response = (HttpWebResponse)httpWebRequest.GetResponse();" 但是,当我尝试“ response =(HttpWebResponse)httpWebRequest.GetResponse();”时 I receive a WebException with the message "The underlying connection was closed: A connection that was expected to be kept alive was closed by the server." 我收到一条带有消息“底层连接已关闭:服务器已关闭的预期保持活动状态的连接”的WebException。

I have found some articles stating that setting the keepalive to false and httpversion to 1.0 resolves the situation. 我发现有些文章指出将keepalive设置为false并将httpversion设置为1.0可以解决这种情况。 I am finding that it does not yeilding the exact same error, plus I do not want to take that approach as I do not want to use the 1.0 version due to how it handles the connection. 我发现它不会产生完全相同的错误,而且我不想采用这种方法,因为由于它如何处理连接,我不想使用1.0版本。

Any suggestions or ideas are welcome. 欢迎任何建议或想法。 I'll try them all until one works! 我会尝试所有这些,直到一个可行!

public ServerResponse PostAttachment(Server server, Database db, Attachment attachment)
    {
        Stream dataStream;
        HttpWebResponse response = null;
        StreamReader sr = null;
        byte[] buffer;
        string json;
        string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
        string headerTemplate = "Content-Disposition: form-data; name=\"_attachments\"; filename=\"" + attachment.Filename + "\"\r\n Content-Type: application/octet-stream\r\n\r\n";
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(headerTemplate);
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");


        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://" + server.Host + ":" + 
            server.Port.ToString() + "/" + db.Name + "/" + attachment.Document.Id);
        httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
        httpWebRequest.Method = "POST";
        httpWebRequest.KeepAlive = true;
        httpWebRequest.ContentLength = attachment.Stream.Length + headerbytes.Length + boundarybytes.Length;

        if (!string.IsNullOrEmpty(server.EncodedCredentials))
            httpWebRequest.Headers.Add("Authorization", server.EncodedCredentials);

        if (!attachment.Stream.CanRead)
            throw new System.NotSupportedException("The stream cannot be read.");

        // Get the request stream
        try
        {
            dataStream = httpWebRequest.GetRequestStream();
        }
        catch (Exception e)
        {
            throw new WebException("Failed to get the request stream.", e);
        }


        buffer = new byte[server.BufferSize];
        int bytesRead;

        dataStream.Write(headerbytes,0,headerbytes.Length); 

        attachment.Stream.Position = 0;
        while ((bytesRead = attachment.Stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            dataStream.Write(buffer, 0, bytesRead);
        }

        dataStream.Write(boundarybytes, 0, boundarybytes.Length);
        dataStream.Close();

        // send the request and get the response
        try
        {
            response = (HttpWebResponse)httpWebRequest.GetResponse();
        }
        catch (Exception e)
        {
            throw new WebException("Invalid response received from server.", e);
        }

        // get the server's response json
        try
        {
            dataStream = response.GetResponseStream();
            sr = new StreamReader(dataStream);
            json = sr.ReadToEnd();
        }
        catch (Exception e)
        {
            throw new WebException("Failed to access the response stream.", e);
        }

        // close up all our streams and response
        sr.Close();
        dataStream.Close();
        response.Close();

        // Deserialize the server response
        return ConvertTo.JsonToServerResponse(json);
    }

After a considerable amount of research on the topic, I have decided to use PUT. 在对该主题进行了大量研究之后,我决定使用PUT。 While Futon uses the POST method, it is undocumented. 尽管Futon使用POST方法,但未记录。 For anyone reading this in the future, use the PUT method, it will make your life much easier. 对于以后阅读此书的任何人,请使用PUT方法,它将使您的生活更加轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取错误“使用HttpWebRequest.GetResponse()进行屏幕抓取时,远程服务器返回错误:(403)禁止” - Getting Error “The remote server returned an error: (403) Forbidden” when screen scraping using HttpWebRequest.GetResponse() HttpWebRequest.GetResponse() 失败时如何获取错误信息 - How to get error information when HttpWebRequest.GetResponse() fails 服务器重定向到未知位置时的HttpWebRequest.GetResponse - HttpWebRequest.GetResponse when server redirects to unknown location 连接失败时使HttpWebRequest.GetResponse()返回一个值 - Make HttpWebRequest.GetResponse() return a value when the connection fails HttpWebRequest.getResponse() 返回 NULL - HttpWebRequest.getResponse() returning NULL Web服务中的httpwebrequest.getResponse超时 - httpwebrequest.getResponse timesout in webservice HttpWebRequest.GetResponse方法卡住了特定的网址 - HttpWebRequest.GetResponse method stucks for specific urls C#HttpWebRequest.GetResponse编码URL - C# HttpWebRequest.GetResponse encoding URL HttpWebRequest.GetResponse方法抛出404异常 - HttpWebRequest.GetResponse methods throws 404 exception 在HttpWebRequest.GetResponse()上生成的动态程序集 - Dynamic assembly generated on HttpWebRequest.GetResponse()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM