C# 网络请求


网络请求第一种方式 : 

var Url = "";

WebRequest wReq = WebRequest.Create(Url);

WebResponse wResp = wReq.GetResponse();

Stream respStream = wResp.GetResponseStream();

using (StreamReader reader = new StreamReader(respStream, Encoding.GetEncoding("UTF-8")))

{

var result = reader.ReadToEnd(); //result就是返回值

}

网络请求第二种方式 : 

   HttpWebRequest request =(HttpWebRequest)WebRequest.Create(Url);

        request.Method = "GET";

       request.ContentType = "text/html;charset=UTF-8";

        request.UserAgent = null;

        // request.Timeout = Timeout;

        HttpWebResponse response =(HttpWebResponse)request.GetResponse();

////获得Response的流

        Stream myResponseStream = response.GetResponseStream();

//读取流数据

        StreamReader myStreamReader = new StreamReader(myResponseStream,Encoding.GetEncoding("utf-8"));

        string retString = myStreamReader.ReadToEnd();

//读取完成  关闭数据流

        myStreamReader.Close();

        myResponseStream.Close();


提交json数据(POST方式):

string Url = "";

string jsonParam = "{\"uid\":\"123456\",\"dappid\":\"dappidasdsad\"}";        

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

request.Method = "POST";      

request.ContentType = "application/json;charset=UTF-8";      

var byteData = Encoding.UTF8.GetBytes(jsonParam);    

var length = byteData.Length;    

request.ContentLength = length;      

var writer = request.GetRequestStream();      

writer.Write(byteData, 0, length);      

writer.Close();      

var response = (HttpWebResponse)request.GetResponse();    

var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();      


2018年12月27日12:06:30

你可能感兴趣的:(C# 网络请求)