您的位置:首页 > 理论基础 > 计算机网络

通过HttpClient调用WebApi的Get、Post方法(返回类型限定为json格式)

2014-03-11 16:50 891 查看
public class HttpClientHelper
{
public static string GetResponseJson(string url)
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result;

if (response.IsSuccessStatusCode)
{
string responseJson = response.Content.ReadAsStringAsync().Result;
return responseJson;
}
else
{
return "出错了,StatusCode:" + response.StatusCode.ToString();
}
}
/// <summary>
        /// 
        /// </summary>
        /// <param name="url">调用的Api地址</param>
        /// <param name="requestJson">表单数据(json格式)</param>
        /// <returns></returns>
public static string PostResponseJson(string url, string requestJson)
{
HttpContent httpContent = new StringContent(requestJson);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient httpClient = new HttpClient();

HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

if (response.IsSuccessStatusCode)
{
string responseJson = response.Content.ReadAsStringAsync().Result;
return responseJson;
}
else
{
return "出错了,StatusCode:" + response.StatusCode.ToString();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HttpClient WebApi
相关文章推荐