在httpwebrequest主体中传递zip文件

时间:2014-01-08 10:34:20

标签: c# curl httpwebrequest zipfile

我正在尝试使用c#代码实现以下cURL调用:

curl -H "Content-Type: application/zip" -u admin:admin -X POST --data-binary @<path to .zip>  http://localhost:606060/content/test.json

我尝试了以下代码,但服务器返回了400个错误的请求代码。

    ___________________________________________________
    MemoryStream postDataStream = new MemoryStream();
    StreamWriter postDataWriter = new StreamWriter(postDataStream);

    postDataWriter.Write("\r\n--" + boundary + "\r\n");
    postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
                            "myFileDescription",
                            "A sample file description");

    // Include the file in the post data
    postDataWriter.Write("\r\n--" + boundary + "\r\n");
    // Include the file in the post data
    postDataWriter.Write("Content-Disposition: form-data;"
                            + "name=\"{0}\";"
                            + "filename=\"{1}\""
                            + "\r\nContent-Type: {2}\r\n\r\n",
                            "myFile",
                            Path.GetFileName(filePath),
                            "application/zip");
    postDataWriter.Flush();

    // Read the file
    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        postDataStream.Write(buffer, 0, bytesRead);
    }
    fileStream.Close();
    postDataWriter.Write("\r\n--" + boundary + "--\r\n");
    postDataWriter.Flush();

    // Set the http request body content length
    request.ContentLength = postDataStream.Length;

    // Dump the post data from the memory stream to the request stream
    using (Stream s = request.GetRequestStream())
    {
        postDataStream.WriteTo(s);
    }
    postDataStream.Close();

    try
    {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        // I am getting exception on this line
        {
    .......................................................................

实际上我在这里使用的代码是用于将文件作为表单参数传递。在我的情况下,没有表单,我明确指定文件路径。我认为我提出请求的方式是错误的。有没有更好的方法来使用与我提供的cURL请求相对应的C#进行httpwebrequest?

文档只说:

  

请求正文必须包含zip文件。

1 个答案:

答案 0 :(得分:1)

您使用的curl命令会在正文中发送整个zip文件内容,简单明了。

您提供的源代码是完全不同的野兽,因为它实现了带有标题和边界的所有多部分formpost内容。看起来你过度了。

使用curl的--trace-ascii选项,您可以准确地看到它发送的内容,您可以更好地发现差异。