C# 使用HttpClient以文件和字符串作为post参数发送HTTP请求

C# 使用HttpClient以文件和字符串作为post参数发送HTTP请求,c#,.net,windows-phone-8.1,C#,.net,Windows Phone 8.1,您好,我正在编写一个Windows Phone 8.1应用程序,在此应用程序中,我需要向Sonic API服务器发送一个请求,请求应包含访问id(字符串)、格式(字符串)和输入文件(mp3文件),我一直坚持将文件和字符串放在一个请求中:这就是我尝试过的: public async static Task<string> RequestSong(StorageFile mp3File, string responseFormat) { try {

您好,我正在编写一个Windows Phone 8.1应用程序,在此应用程序中,我需要向Sonic API服务器发送一个请求,请求应包含访问id(字符串)、格式(字符串)和输入文件(mp3文件),我一直坚持将文件和字符串放在一个请求中:这就是我尝试过的:

public async static Task<string> RequestSong(StorageFile mp3File, string responseFormat)
    {
        try
        {
            using (var webClient = new HttpClient())
            {
                using (var form = new MultipartFormDataContent())
                {
                    var mp3FileByteArray = await readBytesFromStorageFile(mp3File);
                    form.Add(new StringContent(ApiAccessId), "access_id");
                    form.Add(new StringContent(responseFormat), "format");
                    form.Add(new ByteArrayContent(mp3FileByteArray, 0, mp3FileByteArray.Count()), "input_file", mp3File.Name);

                    HttpResponseMessage responseMessage = await webClient.PostAsync(ApiAccessUrl, form);
                    //responseMessage.EnsureSuccessStatusCode();
                    string responseString = responseMessage.Content.ReadAsStringAsync().Result;
                    return responseString;
                }
            }
        }
        catch (Exception e)
        {
            //handle this 
        }

        return "";
    }
public异步静态任务RequestSong(存储文件mp3File,字符串响应格式)
{
尝试
{
使用(var webClient=new HttpClient())
{
使用(var form=new MultipartFormDataContent())
{
var mp3FileByteArray=wait readBytesFromStorageFile(mp3File);
添加(新的StringContent(ApiAccessId),“访问id”);
添加(新的StringContent(responseFormat),“格式”);
添加(新的bytearray内容(mp3FileByteArray,0,mp3FileByteArray.Count()),“输入文件”,mp3File.Name);
HttpResponseMessageResponseMessage=等待webClient.PostAsync(ApiAccessUrl,表单);
//responseMessage.EnsureAccessStatusCode();
字符串responseString=responseMessage.Content.ReadAsStringAsync().Result;
回报率;
}
}
}
捕获(例外e)
{
//处理这个
}
返回“”;
}
请求执行成功,但它表示缺少或错误的访问id,访问id用于访问sonic API,每个用户都有一个唯一的API,我猜这不起作用,因为参数访问id和格式以错误的内容类型放入请求中(只是猜测)。因为如果我将字符串放在formUrlEncodedContent中,它可以正常工作,但我无法上载带有formUrlEncodedContent的文件

是否有任何方法可以在同一请求中发送文件和字符串


顺便说一句,它是System.NET.Http名称空间。

您的访问id应该作为url中的查询字符串参数发送

ApiAccessUrl += "?access_id=" + ApiAccessId;
并删除以下行:

form.Add(new StringContent(ApiAccessId), "access_id");

你有SonicAPI的链接吗?API的协议是什么?当然,先生,这是我想在API中使用的文档。请参阅您发布的链接中的示例url。似乎所有参数都在url中传递。感谢您回复@EZI,是的,所有参数都在url中传递,但是如何传递从wp存储加载的文件?谢谢,但是文件如何?我应该在哪里传递它?就像你处理MultipartFormData的方法一样,api说输入文件丢失了,我很确定我应该通过URL将文件传递到。根据api文档,你需要使用Multipart