C#调用webApi方法

webApi返回Json:在Global.asax.cs文件中,Application_Start() 事件添加=》
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();


1
 public static string HttpPostJsonAPI(string uri, string parameters, string token = "")
        {
            byte[] bytes = Encoding.UTF8.GetBytes(parameters);//这里需要指定提交的编码
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
            webRequest.Method = "POST";
            webRequest.ContentType = "application/json";
            webRequest.Accept = "application/json";
            webRequest.Headers.Add("token", token);
            webRequest.ContentLength = bytes.Length;
            Stream dataStream = webRequest.GetRequestStream();
            dataStream.Write(bytes, 0, bytes.Length);
            dataStream.Close();

            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
            String res = reader.ReadToEnd();
            reader.Close();
            return res.Trim();
        }

2.
string url = "http://192.168.0.192/service/getIpInfo?sex=1";  
HttpWebRequest request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));  
WebResponse response = request.GetResponse();  
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
String res = reader.ReadToEnd(); 
reader.Close();
return res.Trim();

2.
 public static string GetWebAPI(string url, string flag = "")
        {
            string postString = "=3333333";
            byte[] postData = System.Text.Encoding.UTF8.GetBytes(postString); //编码,尤其是汉字,事先要看下抓取网页的编码方式  
            var client = new WebClient();
            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            client.Headers.Add("Accept", "application/json, text/javascript, */*; q=0.01");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可  
            client.Headers.Add("flag", flag); //自定义标识,通过此接口访问则不需要验证.false,标识访问接口不需要验证,true,则相反
            byte[] responseData = client.UploadData(url, "POST", postData); //得到返回字符流  
            string value1 = Encoding.UTF8.GetString(responseData);
            return value1;
        } 

你可能感兴趣的:(C#调用webApi方法)