我们正在使用外部休息 API (Vimeo) 将视频从手机上传到服务器。执行此操作的步骤之一是检查已上传了多少字节。为此,应在带有标头的特定 URL 上执行 PUT 请求:
- 授权承载 d4559ba...
- 内容范围字节 */*
API 的响应是:
- 200 Ok - 如果上传完成
- 308 Resume Incomplete - 带有 Range 标头(例如 Range bytes=0-1000),提供已上传多少字节的信息
问题是 Xamarin 中的枚举 HttpStatusCode ( https://developer.xamarin.com/api/type/System.Net.HttpStatusCode/ ) 不包含值 308 ,因此在调用 client.PutAsync 期间抛出异常:{ System.Net.WebException:无效状态代码:308 ---> System.Net.ProtocolViolationException:无效状态代码:308 在 System.Net.HttpWebRequest.Redirect ... }
知道如何解决此错误吗?这是我们正在使用的 C# 代码:
var client = new HttpClient(new NativeMessageHandler() { AutomaticDecompression = DecompressionMethods.Deflate });
var uri = new Uri(url);
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", Constants.VimeoToken));
var stringContent = new StringContent("");
stringContent.Headers.Add("Content-Range", "bytes */*");
var httpResponse = await client.PutAsync(uri, stringContent);
return httpResponse;
编辑:我尝试将 DelegatingHandler 与此代码一起使用:
public class MyDelegatingHandler : DelegatingHandler
{
public MyDelegatingHandler(HttpMessageHandler innerHandler) : base(innerHandler) { }
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (!response.IsSuccessStatusCode && response.StatusCode == (HttpStatusCode)308) //This line of code is never reached
{
}
return response;
}
}
var client = new HttpClient(new MyDelegatingHandler(new NativeMessageHandler() { AutomaticDecompression = DecompressionMethods.Deflate }));
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Put, url);
var stringContent = new StringContent("");
stringContent.Headers.Add("Content-Range", "bytes */*");
message.Content = stringContent;
CancellationToken cancellationToken = new CancellationToken();
var response = await client.SendAsync(message, cancellationToken);
问题是 base.SendAsync 抛出异常并且没有到达下一行代码(if 语句)。我应该以另一种方式使用委托处理程序吗?
编辑:我尝试将 RestSharp 与此代码一起使用:
RestClient client = new RestClient(url);
var request = new RestRequest("", Method.PUT);
request.AddHeader("Authorization", string.Format("Bearer {0}", Constants.VimeoToken));
request.AddHeader("Content-Range", "bytes */*");
var response = await client.Execute(request);
通过此请求,我收到错误的状态代码,这意味着请求未正确创建。也许 Content-Range 标头未正确添加,Vimeo 服务器无法读取它。还有其他方法可以添加此标头吗?