2018-04-19 get 请求

join suburb

public static string get(string url,int timeout=30000){
     var request=(HttpWebRequest)WebRequest.Create(url);
     request.TimeOut=timeout;
     request.Method="GET";
     request.ConnectType="text/html;charset=UTF-8";
     
     var response=(HttpWebResponse)request.GetResponse(); 
      using(var myResponseStream=response.GetResponseStream())  {
              if(myResponseStream==null) return string.Empty;
              using(var myStreamReader=new   StreamReader(myResponseStream,Encoding.UTF8)){
               return myResponseStream.ReadToEnd();
         }
       }
}

possible

public class ActionToken{
      [JsonProperty(PropertyName="access_token")]
      public string Accesstoken{get;set;}
      [JsonProperty(PropertyName="expires_in")]
      public string Expiresin{get;set;}
}
  public static AccessToken GetToken(string AppID, string AppSecret, string grant_type = "client_credential")
        {
            var url = string.Format(Weixi.getAccessToken, grant_type, AppID, AppSecret);
            return Get(url);

        }
  public static T Get(string url)
        {
            var returnJson = Get(url);
            CheckThrowError(returnJson);
            return GetJson(returnJson);
        }
        /// 
        /// Json字符串转换为对象
        /// 
        /// 
        /// 
        /// 
        public static T GetJson(string jsonString)
        {
            return JsonConvert.DeserializeObject(jsonString);
        }

   public static void CheckThrowError(string returnJson)
        {
            if (returnJson.Contains("errcode"))
            {
                //可能发生错误
                var errorResult = GetJson(returnJson);
                if (errorResult.errcode != ResCode.请求成功)
                {
                    throw new Exception(string.Format("微信请求发生错误!错误代码:{0},说明:{1}", (int)errorResult.errcode, errorResult.errmsg));
                }
            }
        }

补充 实际开发过程中遇到不同的问题

  1. 获取的数据乱码 原因是请求数据 gzip 压缩 需要修改代码
   using (var response = (HttpWebResponse)request.GetResponse())
            {
                var myResponseStream = response.GetResponseStream();
                if (response.ContentEncoding.ToLower() == "gzip")
                {
                    myResponseStream = new GZipStream(myResponseStream, CompressionMode.Decompress);
                }
                if (myResponseStream == null)
                    return string.Empty;
                using (var myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8))
                {
                    return myStreamReader.ReadToEnd();
                }
            }

2.获取某些数据需要授权 需要加上这句

  var request = (HttpWebRequest)WebRequest.Create(url);

  request.Headers.Add("Authorization", token);

你可能感兴趣的:(2018-04-19 get 请求)