通过HttpWebRequest调用api接口

using System.Net;
using System.IO;
using System.Text;

通过HttpWebRequest调用api接口

/// <summary>
/// 通过HttpWebRequest调用api接口
/// </summary>
/// <returns></returns>
static string HttpGet()
{
string retStr = "";
HttpWebRequest request = null;
try
{
string fullUrl = "https://api.xx.com/";
request = (HttpWebRequest)HttpWebRequest.Create(fullUrl);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 3600;
request.ReadWriteTimeout = 3600;
retStr = ReadStringResponse(request.GetResponse());
}
catch (Exception ex)
{
throw ex;
}
return retStr;
}

解析web响应,以string形式返回

/// <summary>
/// 解析web响应,以string形式返回
/// </summary>
/// <param name="response">web响应</param>
/// <returns>返回string形式的web响应</returns>
private static String ReadStringResponse(WebResponse response)
{
string returnStr = "";
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
returnStr = sr.ReadToEnd();
sr.Close();
return returnStr;
}
© 版权声明
THE END
喜欢就支持一下吧
点赞11赞赏
分享
评论 抢沙发

请登录后发表评论