zoukankan      html  css  js  c++  java
  • c# 请求api获得json数据

        public class HttpUitls
        {
            public static string Get(string Url)
            {
                //System.GC.Collect();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Proxy = null;
                request.KeepAlive = false;
                request.Method = "GET";
                request.ContentType = "application/json; charset=UTF-8";
                request.AutomaticDecompression = DecompressionMethods.GZip;
    
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
    
                myStreamReader.Close();
                myResponseStream.Close();
    
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
    
                return retString;
            }
    
            public static string Post(string Url, string Data, string Referer)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.Referer = Referer;
                byte[] bytes = Encoding.UTF8.GetBytes(Data);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = bytes.Length;
                Stream myResponseStream = request.GetRequestStream();
                myResponseStream.Write(bytes, 0, bytes.Length);
    
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
    
                myStreamReader.Close();
                myResponseStream.Close();
    
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
                return retString;
            }
        }
    string json = HttpUitls.Post("http://music.163.com/api/search/pc", string.Format("s={0}&offset={1}&limit={2}&type={3}", key, "0", "10", "1"), "http://music.163.com/");
  • 相关阅读:
    Linux部署Apache ActiveMQ 5.14.1
    数据库iops的理解
    IOPS性能指标
    APK反编译工具与使用方法
    App Inspector-iOS真机
    idea 项目maven无法拉取jar
    adb shell常用命令
    ADB 在APP自动化测试应用汇总
    java调用shell命令并获取执行结果的示例
    分享几个特别实用的网站,分分钟钟提升个人技能
  • 原文地址:https://www.cnblogs.com/margin-gu/p/5887509.html
Copyright © 2011-2022 走看看