异步正确获取Web响应状态码
Get Web Response Status Code properly Asynchronously
我正在 C# 或 VB.Net 中寻找此问题的解决方案。
使用 WebClient
我想异步检索 UploadValuesAsync
方法的服务器响应,但我不知道该怎么做。
基本上我想在这个问题上做同样的事情,将响应代码作为整数(但异步):
示例代码:
下面代码的问题与我链接的另一个问题中暴露的问题相同,如果 e.result
属性 不正确,它会抛出异常,然后我无法解析任何200 代码以外的其他状态代码,因为该异常。
我已经在 e.Error
异常上搜索了 Response
属性,但我没有找到任何东西,所以我无法继续。
AddHandler wc.UploadValuesCompleted, AddressOf WC_UploadValuesCompleted
wc.UploadValuesAsync(New Uri("https://api.imgur.com/3/upload.xml"), values)
然后:
Private Sub WC_UploadValuesCompleted(ByVal sender As Object, ByVal e As UploadValuesCompletedEventArgs)
If Not e.Cancelled Then
Dim responseAsync As Byte() = e.Result
' Read the response (Converting Byte-Array to Stream).
Using sr As New StreamReader(New MemoryStream(responseAsync))
Dim serverResponse As String = sr.ReadToEnd
Dim xdoc As New XDocument(XDocument.Parse(serverResponse))
Dim status As ImgurStatus = Nothing
status = Me.GetResultFromStatus(Convert.ToInt32(xdoc.Root.LastAttribute.Value.ToString))
Select Case status
Case ImgurStatus.Success ' 200
Return New ImgurImage(New Uri(xdoc.Descendants("link").Value))
Case ImgurStatus.AccessForbidden ' 403
RaiseEvent OnAccessForbidden(Me, ImgurStatus.AccessForbidden)
Case ImgurStatus.AuthorizationFailed ' 401
RaiseEvent OnAuthorizationFailed(Me, ImgurStatus.AuthorizationFailed)
Case ImgurStatus.BadImageFormat ' 400
RaiseEvent OnBadImageFormat(Me, ImgurStatus.BadImageFormat)
Case ImgurStatus.InternalServerError ' 500
RaiseEvent OnInternalServerError(Me, ImgurStatus.InternalServerError)
Case ImgurStatus.PageIsNotFound ' 404
RaiseEvent OnPageIsNotFound(Me, ImgurStatus.PageIsNotFound)
Case ImgurStatus.UploadRateLimitError ' 429
RaiseEvent OnUploadRateLimitError(Me, ImgurStatus.UploadRateLimitError)
Case ImgurStatus.UnknownError ' -0
RaiseEvent OnUnknownError(Me, ImgurStatus.UnknownError)
Return Nothing
End Select
End Using '/ sr As New StreamReader
End If
End Sub
下面的代码对我有用(使用 Json.Net):
async private void button1_Click(object sender, EventArgs e)
{
var response = await UploadToImgUrl(filename, client_id);
}
async Task<ImgUrl.Response> UploadToImgUrl(string fname, string client_id)
{
string endPoint = "https://api.imgur.com/3/upload";
var data = Convert.ToBase64String(File.ReadAllBytes(fname));
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Client-ID " + client_id);
var resp = await client.PostAsJsonAsync(endPoint, new { image = data, type= "base64", name = new FileInfo(fname).Name });
var content = await resp.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<ImgUrl.Response>(content);
}
}
public class ImgUrl
{
public class Data
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Datetime { get; set; }
public string Type { get; set; }
public bool Animated { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Size { get; set; }
public int Views { get; set; }
public int Bandwidth { get; set; }
public string Deletehash { get; set; }
public string Name { get; set; }
public string Link { get; set; }
}
public class Response
{
public Data Data { get; set; }
public bool Success { get; set; }
public int Status { get; set; }
}
}
我正在 C# 或 VB.Net 中寻找此问题的解决方案。
使用 WebClient
我想异步检索 UploadValuesAsync
方法的服务器响应,但我不知道该怎么做。
基本上我想在这个问题上做同样的事情,将响应代码作为整数(但异步):
示例代码:
下面代码的问题与我链接的另一个问题中暴露的问题相同,如果 e.result
属性 不正确,它会抛出异常,然后我无法解析任何200 代码以外的其他状态代码,因为该异常。
我已经在 e.Error
异常上搜索了 Response
属性,但我没有找到任何东西,所以我无法继续。
AddHandler wc.UploadValuesCompleted, AddressOf WC_UploadValuesCompleted
wc.UploadValuesAsync(New Uri("https://api.imgur.com/3/upload.xml"), values)
然后:
Private Sub WC_UploadValuesCompleted(ByVal sender As Object, ByVal e As UploadValuesCompletedEventArgs)
If Not e.Cancelled Then
Dim responseAsync As Byte() = e.Result
' Read the response (Converting Byte-Array to Stream).
Using sr As New StreamReader(New MemoryStream(responseAsync))
Dim serverResponse As String = sr.ReadToEnd
Dim xdoc As New XDocument(XDocument.Parse(serverResponse))
Dim status As ImgurStatus = Nothing
status = Me.GetResultFromStatus(Convert.ToInt32(xdoc.Root.LastAttribute.Value.ToString))
Select Case status
Case ImgurStatus.Success ' 200
Return New ImgurImage(New Uri(xdoc.Descendants("link").Value))
Case ImgurStatus.AccessForbidden ' 403
RaiseEvent OnAccessForbidden(Me, ImgurStatus.AccessForbidden)
Case ImgurStatus.AuthorizationFailed ' 401
RaiseEvent OnAuthorizationFailed(Me, ImgurStatus.AuthorizationFailed)
Case ImgurStatus.BadImageFormat ' 400
RaiseEvent OnBadImageFormat(Me, ImgurStatus.BadImageFormat)
Case ImgurStatus.InternalServerError ' 500
RaiseEvent OnInternalServerError(Me, ImgurStatus.InternalServerError)
Case ImgurStatus.PageIsNotFound ' 404
RaiseEvent OnPageIsNotFound(Me, ImgurStatus.PageIsNotFound)
Case ImgurStatus.UploadRateLimitError ' 429
RaiseEvent OnUploadRateLimitError(Me, ImgurStatus.UploadRateLimitError)
Case ImgurStatus.UnknownError ' -0
RaiseEvent OnUnknownError(Me, ImgurStatus.UnknownError)
Return Nothing
End Select
End Using '/ sr As New StreamReader
End If
End Sub
下面的代码对我有用(使用 Json.Net):
async private void button1_Click(object sender, EventArgs e)
{
var response = await UploadToImgUrl(filename, client_id);
}
async Task<ImgUrl.Response> UploadToImgUrl(string fname, string client_id)
{
string endPoint = "https://api.imgur.com/3/upload";
var data = Convert.ToBase64String(File.ReadAllBytes(fname));
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Client-ID " + client_id);
var resp = await client.PostAsJsonAsync(endPoint, new { image = data, type= "base64", name = new FileInfo(fname).Name });
var content = await resp.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<ImgUrl.Response>(content);
}
}
public class ImgUrl
{
public class Data
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Datetime { get; set; }
public string Type { get; set; }
public bool Animated { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Size { get; set; }
public int Views { get; set; }
public int Bandwidth { get; set; }
public string Deletehash { get; set; }
public string Name { get; set; }
public string Link { get; set; }
}
public class Response
{
public Data Data { get; set; }
public bool Success { get; set; }
public int Status { get; set; }
}
}