using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace TempTask.WebEntry.Tools
{
    /// <summary>
    /// 
    /// </summary>
    public class HttpHelper
    {

        /// <summary>
        /// 请求网页地址
        /// </summary>
        /// <param name="url">网页地址</param>
        /// <param name="method"></param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public static string CallUrl(string url, string method, string param)
        {
            //创建一个HTTP请求  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            //Post请求方式  
            request.Method = method;
            //内容类型
            request.ContentType = "application/json";

            //byte[] bs = Encoding.ASCII.GetBytes(param);    //参数转化为ascii码
            byte[] bs = Encoding.UTF8.GetBytes(param);
            request.ContentLength = bs.Length;
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }

            String strValue = "";//strValue为http响应所返回的字符流
            HttpWebResponse response;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }
            using Stream s = response.GetResponseStream();
            using StreamReader sr = new StreamReader(s);
            strValue = sr.ReadToEnd();
            return strValue;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string CallUrl(string url, string param)
        {
            WebClient webClient = new WebClient();
            return webClient.DownloadString(url + (url.Contains("?") ? "&" : "?") + param);
        }
    }
}
