使用WebRequest代替curl命令

时间:2013-03-24 21:56:06

标签: c# curl

我正在开发一个项目,该项目需要使用curl命令将文件加载到特定站点。我希望这可以使用C#实现。通过查看关于SO的类似问题,我没有找到任何似乎对我有用的东西,除非我做错了。

这是我成功用于Cygwin的curl命令:

curl -i -u user:password -F 'file1=@\Users\User\Desktop\test.jpg' -F 'json={"content": {"type": "text/html", "text": "<body><p>look at me, look at me</p></body>"}, "type": "document", "subject": "Document with Attachment"};type=application/json' http://someurl

现在我正在尝试使用WebRequest进行此工作,因为我已经读过这可能在其他帖子上。这就是我到目前为止所做的。

 WebRequest request = WebRequest.Create("http://someurl");
            request.PreAuthenticate = true;
            request.ContentType = "application/json";
            request.Method = "POST";
            string authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes("user:password"));
            request.Headers["Authorization"] = "Basic " + authInfo;

            //what do I set my buffer to?

            Stream reqstr = request.GetRequestStream();
            reqstr.Write(buffer, 0, buffer.Length);
            reqstr.Close();

            WebResponse response = request.GetResponse();

我将缓冲区设置为何处以编写curl命令,而curl命令又应该发送文件test.jpg?此外,我尝试使用libcurl也没有成功。任何指向正确的方向都非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以先发布POST json文档描述,然后使用第二个请求PUT文件内容, 或使用multipart / form-data以单个POST上传两者。

这篇文章有很好的示例:How do I add/create/insert files to Google Drive through the API?