C#.NET中的异步POST请求

C#.NET中的异步POST请求,c#,post,asynchronous,request,httpclient,C#,Post,Asynchronous,Request,Httpclient,我正在尝试使用HttpClient/HttpContent通过网络上传数据 然而,我似乎找不到一个合适的方式来发送文件这种方式 这是我目前的代码: private async Task<APIResponse> MakePostRequest(string RequestUrl, string Content) { HttpClient httpClient = new HttpClient(); HttpContent httpCo

我正在尝试使用HttpClient/HttpContent通过网络上传数据 然而,我似乎找不到一个合适的方式来发送文件这种方式

这是我目前的代码:

    private async Task<APIResponse> MakePostRequest(string RequestUrl, string Content)
    {
        HttpClient  httpClient = new HttpClient();
        HttpContent httpContent = new StringContent(Content);
        APIResponse serverReply = new APIResponse();

        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        try {
            Console.WriteLine("Sending Request: " + RequestUrl + Content);
            HttpResponseMessage response = await httpClient.PostAsync(RequestUrl, httpContent).ConfigureAwait(false);
        }
        catch (HttpRequestException hre)
        {
            Console.WriteLine("hre.Message");
        }
        return (serverReply);
    }
我做错什么了吗?是否有其他更好的方法来创建正确的POST请求(必须是异步的,并且支持文件上传)


谢谢。

您需要以base64编码字符串的形式发送数据吗?如果您发送的是任意字节(即照片),如果您使用
ByteArrayContent
类,则可以不编码地发送它们:

private async Task<APIResponse> MakePostRequest(string RequestUrl, byte[] Content)
{
    HttpClient  httpClient = new HttpClient();
    HttpContent httpContent = new ByteArrayContent(Content);
    APIResponse serverReply = new APIResponse();

    try {
        Console.WriteLine("Sending Request: " + RequestUrl + Content);
        HttpResponseMessage response = await httpClient.PostAsync(RequestUrl, httpContent).ConfigureAwait(false);
        // do something with the response, like setting properties on serverReply?
    }
    catch (HttpRequestException hre)
    {
        Console.WriteLine("hre.Message");
    }

    return (serverReply);
}
private异步任务MakePostRequest(字符串RequestUrl,字节[]内容)
{
HttpClient HttpClient=新HttpClient();
HttpContent HttpContent=新的ByteArrayContent(内容);
APIResponse serverReply=新的APIResponse();
试一试{
Console.WriteLine(“发送请求:+RequestUrl+内容”);
HttpResponseMessage response=等待httpClient.PostAsync(请求URL,httpContent).ConfigureAwait(false);
//对响应执行一些操作,例如在serverReply上设置属性?
}
捕获(HttpRequestException hre)
{
Console.WriteLine(“hre.Message”);
}
返回(serverReply);
}

主要问题可能是因为我混合了字符串和文件数据

这就解决了它:

    public async Task<bool> CreateNewData (Data nData)
    {
        APIResponse serverReply;

        MultipartFormDataContent form = new MultipartFormDataContent ();

        form.Add (new StringContent (_partnerKey), "partnerKey");
        form.Add (new StringContent (UserData.Instance.key), "key");
        form.Add (new StringContent (nData.ToJson ()), "erList");

        if (nData._FileLocation != null) {
            string good_path = nData._FileLocation.Substring (7); // Dangerous
            byte[] PictureData = File.ReadAllBytes (good_path);
            HttpContent content = new ByteArrayContent (PictureData);
            content.Headers.Add ("Content-Type", "image/jpeg");
            form.Add (content, "picture_0", "picture_0");
        }

        form.Add (new StringContent (((int)(DateTime.Now.ToUniversalTime () -
            new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds).ToString ()), "time");
        serverReply = await MakePostRequest (_baseURL + "Data-report/create", form);

        if (serverReply.Status == SERVER_OK)
            return (true);
        Android.Util.Log.Error ("MyApplication", serverReply.Response);
        return (false);
    }

    private async Task<APIResponse> MakePostRequest (string RequestUrl, MultipartFormDataContent Content)
    {
        HttpClient httpClient = new HttpClient ();
        APIResponse serverReply = new APIResponse ();

        try {
            Console.WriteLine ("MyApplication - Sending Request");
            Android.Util.Log.Info ("MyApplication", " Sending Request");
            HttpResponseMessage response = await httpClient.PostAsync (RequestUrl, Content).ConfigureAwait (false);
            serverReply.Status = (int)response.StatusCode;
            serverReply.Response = await response.Content.ReadAsStringAsync ();
        } catch (HttpRequestException hre) {
            Android.Util.Log.Error ("MyApplication", hre.Message);
        }
        return (serverReply);
    }
公共异步任务CreateNewData(数据数据数据)
{
APIResponse服务器应答;
MultipartFormDataContent form=新的MultipartFormDataContent();
添加(新的StringContent(_partnerKey),“partnerKey”);
Add(新的StringContent(UserData.Instance.key),“key”);
Add(新的StringContent(nData.ToJson()),“erList”);
如果(数据。\u文件位置!=null){
字符串good_path=nda._FileLocation.Substring(7);//危险
byte[]PictureData=File.ReadAllBytes(良好路径);
HttpContent=新的ByteArrayContent(图片数据);
content.Headers.Add(“内容类型”、“图像/jpeg”);
增加(内容,“图片0”、“图片0”);
}
Add(新的StringContent((int)(DateTime.Now.ToUniversalTime)()-
新的日期时间(1970,1,1,0,0,0,DateTimeKind.Utc)).TotalSeconds.ToString(),“time”);
serverReply=等待MakePostRequest(_baseURL+“数据报告/创建”,表单);
if(serverReply.Status==SERVER\u OK)
返回(真);
Android.Util.Log.Error(“MyApplication”,serverReply.Response);
返回(假);
}
专用异步任务MakePostRequest(字符串RequestUrl,MultipartFormDataContent)
{
HttpClient-HttpClient=新的HttpClient();
APIResponse serverReply=新的APIResponse();
试一试{
Console.WriteLine(“我的应用程序-发送请求”);
Android.Util.Log.Info(“MyApplication”、“发送请求”);
HttpResponseMessage response=等待httpClient.PostAsync(请求URL,内容)。配置等待(false);
serverReply.Status=(int)response.StatusCode;
serverReply.Response=wait Response.Content.ReadAsStringAsync();
}捕获(HttpRequestException hre){
Android.Util.Log.Error(“MyApplication”,hre.Message);
}
返回(serverReply);
}

主要使用多部分内容、设置内容类型和遍历字节数组似乎已经完成了这项工作。

我将在同一请求中发送字符串、JSON数组和照片。这有关系吗?也不要担心响应,我设置了它,我只是从代码中删除了部分,因为它不是真正相关的。是的,它很重要。服务器如何期望字符串和数组参数?作为HTTP头,作为正文的一部分,还有其他方式吗?客户端必须以服务器期望的方式发送请求。
    public async Task<bool> CreateNewData (Data nData)
    {
        APIResponse serverReply;

        MultipartFormDataContent form = new MultipartFormDataContent ();

        form.Add (new StringContent (_partnerKey), "partnerKey");
        form.Add (new StringContent (UserData.Instance.key), "key");
        form.Add (new StringContent (nData.ToJson ()), "erList");

        if (nData._FileLocation != null) {
            string good_path = nData._FileLocation.Substring (7); // Dangerous
            byte[] PictureData = File.ReadAllBytes (good_path);
            HttpContent content = new ByteArrayContent (PictureData);
            content.Headers.Add ("Content-Type", "image/jpeg");
            form.Add (content, "picture_0", "picture_0");
        }

        form.Add (new StringContent (((int)(DateTime.Now.ToUniversalTime () -
            new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds).ToString ()), "time");
        serverReply = await MakePostRequest (_baseURL + "Data-report/create", form);

        if (serverReply.Status == SERVER_OK)
            return (true);
        Android.Util.Log.Error ("MyApplication", serverReply.Response);
        return (false);
    }

    private async Task<APIResponse> MakePostRequest (string RequestUrl, MultipartFormDataContent Content)
    {
        HttpClient httpClient = new HttpClient ();
        APIResponse serverReply = new APIResponse ();

        try {
            Console.WriteLine ("MyApplication - Sending Request");
            Android.Util.Log.Info ("MyApplication", " Sending Request");
            HttpResponseMessage response = await httpClient.PostAsync (RequestUrl, Content).ConfigureAwait (false);
            serverReply.Status = (int)response.StatusCode;
            serverReply.Response = await response.Content.ReadAsStringAsync ();
        } catch (HttpRequestException hre) {
            Android.Util.Log.Error ("MyApplication", hre.Message);
        }
        return (serverReply);
    }