c# - 使用 HttpWebRequest.GetResponse 时出现 KeepAliveException

标签 c# httpwebrequest couchdb getresponse

我正在尝试使用 HttpWebRequest 将附件发布到 CouchDB。但是,当我尝试“response = (HttpWebResponse)httpWebRequest.GetResponse();”时我收到一个 WebException 消息“底层连接已关闭:服务器关闭了预期保持事件状态的连接。”

我发现一些文章指出将 keepalive 设置为 false 并将 httpversion 设置为 1.0 可以解决这种情况。我发现它不会产生完全相同的错误,而且我不想采用这种方法,因为由于它处理连接的方式,我不想使用 1.0 版本。

欢迎提出任何建议或想法。我会尝试所有方法,直到一个有效!

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

最佳答案

在对该主题进行了大量研究之后,我决定使用 PUT。虽然 Futon 使用 POST 方法,但它没有记录。对于以后阅读本文的任何人,请使用 PUT 方法,这将使您的生活更加轻松。

关于c# - 使用 HttpWebRequest.GetResponse 时出现 KeepAliveException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2560273/

相关文章:

javascript - CouchDB 使用分块编码和 jQuery ajax()

c# - 类似于 C# 的 Java SimpleDateFormat

c# - 是否可以在 C# 中更改 HTTP header 的顺序(使用任何外部库)?

mongodb - 将遗留 EAV 模式转换为 Mongo 或 Couch

c# - 请求被中止 : Could not create SSL/TLS secure channel

java - 如果网页已更新,则发出警报

java - 如何使用 java 在 Couchdb 中存储原始 JSON

c# - 将对象分配给c#中的treeview子节点以识别父节点

c# - 为什么 null 条件运算符对 == 和 .Equals() 的行为不同?

c# - MongoDB C# 2.1 ReplaceOneAsync 不适用于存储库模式