winform调用http

 

 

一、post请求实现  


public static string PostHttp(string url, string jsonParmaData)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            try
            {
                
                NetworkCredential auth = new NetworkCredential("admin", "www.hd123.com");//添加此代码

                var postData = Encoding.UTF8.GetBytes(jsonParmaData);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
                httpWebRequest.Timeout = 10000;
                httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
                httpWebRequest.Credentials = auth;//添加认证

                httpWebRequest.ContentLength = postData.Length;
                httpWebRequest.GetRequestStream().Write(postData, 0, postData.Length);
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
              
 using (Stream stream = httpWebResponse.GetResponseStream()) 
{ 


using (StreamReader sr = new StreamReader(stream, Encoding.UTF8)) 
{ string str = sr.ReadToEnd(); 
sr.Close(); 
stream.Close(); 
httpWebResponse.Close(); 
return str;
 }

}
 
} catch (Exception ex)
 {
   try { httpWebRequest.Abort(); } catch { } 
} 
return null;

 } 
 
View Code

 

 

posted on 2017-07-11 01:03  木色小罗  阅读(462)  评论(0编辑  收藏  举报

导航

诗与远方