WebClient.UploadData"基础连接已关闭"

时间:2014-07-17 17:28:16

标签: vb.net webclient basecamp

我尝试使用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。

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

1 个答案:

答案 0 :(得分:1)

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