我正在尝试使用 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);
}
内容是以下形式的字符串:paramname=value¶m2name=value¶m3name=value.. 重点是我必须通过这个请求实际发送一个文件(照片)。
似乎每个参数都可以正常工作,但文件本身(我必须在发布请求中发送两个身份验证 key ,并且它们被识别)
我以这种方式将图片作为字符串进行检索,这可能是它失败的主要原因之一? :/
byte[] PictureData = File.ReadAllBytes(good_path);
string encoded = Convert.ToBase64String(PictureData);
我做错了什么吗?是否有另一种更好的方法来创建正确的 POST 请求(它必须是异步的并支持文件上传)
谢谢。
最佳答案
主要问题可能是我混合了字符串和文件数据。
这解决了它:
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);
}
主要使用 Multipart Content,设置 Content Type 和遍历字节数组似乎已经完成了工作。
关于c# - C# .NET 中的异步 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15706736/