【问题标题】:WebClient.UploadData "The underlying connection was closed"WebClient.UploadData "底层连接已关闭"
【发布时间】:2014-07-17 17:28:15
【问题描述】:

我正在尝试使用 Basecamp API 将文件从 FTP 站点上传到 Basecamp。我正在使用一个简单的控制台应用程序。这是我的代码:

Try
    Dim accountID As String = ConfigurationManager.AppSettings("BaseCampID")
    Dim projectID As Integer = 9999999
    Dim folderName As String = "XXXXX/XXXXX"
    Dim fileName As String = "XXX.zip"

    'The URL to access the attachment method of the API
    Dim apiURL = String.Format("https://basecamp.com/{0}/api/v1/projects/{1}/attachments.json", accountID, projectID)

    'Get the file from the FTP server as a byte array
    Dim fileBytes As Byte() = GetFileBytes(String.Format("{0}\\{1}", folderName, fileName))

    'Initialize the WebClient object
    Dim client As New WebClient()
    client.Headers.Add("Content-Type", "application/zip")
    'Need to provide a user-agent with a URL or email address
    client.Headers.Add("User-Agent", "Basecamp Upload (email@email.com)")
    'Keep the connection alive so it doesn't close
    client.Headers.Add("Keep-Alive", "true")

    'Provide the Basecamp credentials
    client.Credentials = New NetworkCredential("username", "password")

    'Upload the file as a byte array to the API, and get the response
    Dim responseStr As Byte() = client.UploadData(apiURL, "POST", fileBytes)

    'Convert the JSON response to a BaseCampAttachment object
    Dim attachment As BaseCampAttachment
    attachment = JSonHelper.FromJSon(Of BaseCampAttachment)(Encoding.Default.GetString(responseStr))

Catch ex As Exception
    Console.WriteLine(ex.Message)
Finally
    Console.ReadLine()
End Try

但每当它调用 client.UploadData 时,我都会收到错误消息“底层连接已关闭:连接已意外关闭。”我早些时候遇到了这个问题,并认为我通过添加“Keep-Alive”标题解决了这个问题,但它不再起作用了。如果我使用 client.UploadFile 上传本地文件,API 可以工作,但我只想从 FTP 的字节数组上传文件,而不是在本地下载文件然后上传到 Basecamp。

任何想法将不胜感激。谢谢!

【问题讨论】:

  • 所以您是说上面的代码在您的机器上运行时有效,但在您从 FTP 服务器运行时无效?除了连接关闭之外,您是否收到任何特定的 HTTP 响应代码或消息?
  • 当天早些时候它在我的机器上运行,但在某个时候它开始在我的机器上收到连接关闭消息。除了连接关闭之外,我没有看到任何其他 HTTP 响应代码。

标签: vb.net webclient basecamp


【解决方案1】:

我从来没有弄清楚 WebClient 调用出了什么问题,但我最终使用了来自 https://basecampwrapper.codeplex.com 的 Basecamp API 包装器。该包装器使用 HTTPRequest 和 HTTPResponse 而不是 WebClient.UploadData。使用该包装器也比尝试从头开始编写我自己的代码要容易得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-31
    • 2018-01-31
    • 2017-09-21
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多