当我试图封装一个.net http客户端休息助手时遇到了一个问题,我只是不知道问题出在哪里,有人会这么善意提供帮助。 下面的助手班:
public class RestHelper
{
private string BuildApiUriFromRequest(HttpRequestBase request)
{
return request.Url.ToString();
}
private static IEnumerable<KeyValuePair<string, string>> GetFromForm(NameValueCollection form)
{
if (form == null) return null;
Dictionary<string, string> nameValueCollection = new Dictionary<string, string>();
form.AllKeys.ToList().ForEach(key =>
{
nameValueCollection.Add(key, form[key]);
});
return nameValueCollection;
}
public static void Get(string url, Action<string> customise)
{
RestMethod(url, null, customise, (httpClient, requestUrl, httpContent) =>
{
return httpClient.GetAsync(requestUrl);
});
}
public static void Post(string url, NameValueCollection form, Action<string> customise)
{
RestMethod(url, form, customise, (httpClient, requestUrl, httpContent) => { return httpClient.PostAsync(requestUrl, httpContent); });
}
public static void Put(string url, NameValueCollection form, Action<string> customise)
{
RestMethod(url, form, customise, (httpClient, requestUrl, httpContent) => { return httpClient.PutAsync(requestUrl, httpContent); });
}
public static void Delete(string url, Action<string> customise)
{
RestMethod(url, null, customise, (httpClient, requestUrl, httpContent) => { return httpClient.DeleteAsync(requestUrl); });
}
public static void RestMethod(HttpRequestBase request, Action<string> customise)
{
Get(request.Url.ToString(), customise);
}
public static void RestMethod(string url, NameValueCollection form, Action<string> customise, Func<HttpClient, string, HttpContent, Task<HttpResponseMessage>> getResponseHttpMessage)
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var client = new HttpClient(handler))
{
FormUrlEncodedContent content = null;
if (form != null)
{
IEnumerable<KeyValuePair<string, string>> nameValueCollection = GetFromForm(form);
content = new FormUrlEncodedContent(nameValueCollection);
}
HandleResult(client, url, content, customise, getResponseHttpMessage);
}
}
private static void HandleResult(HttpClient client, string url, FormUrlEncodedContent content, Action<string> customise, Func<HttpClient, string, HttpContent, Task<HttpResponseMessage>> getResponseHttpMessage)
{
getResponseHttpMessage(client, url, content).ContinueWith(httpResponseMessage =>
{
try
{
httpResponseMessage.Result.EnsureSuccessStatusCode();
httpResponseMessage.Result.Content.ReadAsStringAsync().ContinueWith(readTask =>
{
customise(readTask.Result);
});
}
catch (Exception ex)
{
customise(ex.Message);
}
});
}
}
当我遇到一些问题时,我正在测试get方法,它似乎是委托异常,但编译器没有显示更多异常细节, 然后我尝试使用带有continue-with方法的原始httpclient,并且请求返回了正确的结果json字符串。关于httphandler,我错了吗?使用纯http客户端可能没问题?但我希望它更苗条......