当前位置: 首页 > 编程语言 > C#

C#中的Curl-F等价物Share

时间:2023-04-10 18:35:57 C#

C#中的curl-F等价物这是CURL命令:curl-XPOSThttps://zzz.zzz.zzz/yyy-FKey=abcd-Fmedia=@"audio.aac"我写了以下代码:usingSystem;使用System.Collections.Generic;使用System.Linq;使用系统文本;使用System.Threading.Tasks;使用System.Net.Http;使用System.IO;使用System.Net.Http.Headers;命名空间Speech2Text{类程序{staticvoidMain(string[]args){curl().Wait();}staticasyncTaskcurl(){varclient=newHttpClient();//创建键值对列表ListbodyProperties=newList();bodyProperties.Add(newKeyValuePair("key","abcd"));bodyProperties.Add(newKeyValuePair("media","@audio.aac"));vardataContent=newFormUrlEncodedContent(bodyProperties.ToArray());HttpResponseMessageresponse=awaitclient.PostAsync("https://zzz.zzz.zzz/yyy",dataContent);HttpContentresponseContent=response.Content;使用(varreader=newStreamReader(awaitresponseContent.ReadAsStreamAsync())){Console.WriteLine(等待读者。ReadToEndAsync());但我一直这样说:{"code":400,"message":"Pleaseuse[media]forthemediafilefieldnameinyourPOSTrequest."}dataContect变量是否有问题,或者还有什么?发送POST时,发送到服务器的Content-Type确实是服务器所期望的非常重要您可以使用curl中的-trace选项轻松验证发送的内容:curl-v--trace--XPOSThttp://localhost-FKey=abcd-Fmedia=@"image.txt"当你运行它时,你会在前几行的某处找到:00b0:636f6e74696e75650d0a436f6e74656econtinue..Conten00c0:742d547970653a206d756c7469706172t-Type:multipar00d0:742f666f726d2d646174613b20626f75t/表格数据;ndary=------------00f0:2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d--------------0100:2d2d6161626466316666383566660d0a--aabdf1ff85ff..0110:0d0a..所以curl正在发送一个内容类型的多部分/表单数据;在您使用FormUrlEncodedContent类的代码中,FormUrlEncodedContent在其描述中指出:使用application/x-www-form-urlencodedMIME类型编码的名称/值元组的容器。所以这不是正确的内容类型。更好的匹配是MultipartFormDataContent,因为它指出:为使用multipart/form-dataMIME类型编码的内容提供容器。一旦找到合适的类,我们只需要构建容器:vardataContent=newMultipartFormDataContent();varkeyValue=newByteArrayContent(Encoding.ASCII.GetBytes("abcd"));dataContent.Add(keyValue,"key");using(varclient=newHttpClient()){//打开你的文件using(varfs=File.OpenRead(@"c:pathtoaudio.acc")){//从文件创建StreamContentvarfileValue=newStreamContent(fs);//添加名称和元数据dataContent.Add(fileValue,"media","audio.acc");HttpResponseMessageresponse=awaitclient.PostAsync("http://yoursite.org",dataContent);HttpContentresponseContent=response.Content;使用(varreader=newStreamReader(awaitresponseContent.ReadAsStreamAsync())){Console.WriteLine(awaitreader.ReadToEndAsync());}}}运行此代码在Fiddler中显示:POST/HTTP/1.1Content-Type:multipart/form-data;boundary="f7335f00-bc16-4518-ae7a-149491403792"主机:yoursite.org内容长度:1014预期:100-continue连接:Keep-Alive--f7335f00-bc16-4518-ae7a-149491403792内容配置:表单数据;name=keyabcd--f7335f00-bc16-4518-ae7a-149491403792Content-Disposition:form-data;名称=媒体;文件名=audio.acc;filename*=utf-8''audio.acc这个比较符合curl的跟踪输出。以上就是《C#学习教程:C#中的Curl-F等价物》的全部内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多加关注——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: