RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:9:30-18:00
你可能遇到了下面的问题
关闭右侧工具栏
.net调用别人的http页面,返回结果,url中有中文的
  • 作者:xiaoxiao
  • 发表时间:2020-12-23 11:02
  • 来源:未知

一 get方法。

using System;using System.Net;using System.IO;using System.Text;using System.Web;using MSXML2;using System.Threading;

namespace Engine.Activity.FeeAgency{ /// <summary> /// Summary description of Class GetHttp. /// </summary> public class GetHttp {  private GetHttp()  {  }    public static string Get_Http(string a_strUrl)   {   string strResult ;    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(a_strUrl);   myReq.Method="GET";   try    {    HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();

    Stream myStream = HttpWResp.GetResponseStream() ;     StreamReader sr = new StreamReader(myStream , Encoding.Default);     StringBuilder strBuilder = new StringBuilder();     while (-1 != sr.Peek())     {     strBuilder.Append(sr.ReadLine());     }

    strResult = strBuilder.ToString();    }    catch(Exception exp)    {       strResult = "错误:" + exp.Message ;    }

   return strResult ;

  }  }

}

二 post方法,可以处理中文的url

using System;using System.Net;using System.IO;using System.Text;using System.Web;using MSXML2;using System.Threading;

namespace Engine.Activity.FeeAgency{ public class PostHttp {  private PostHttp()  {  }   public static string Post_Http(string a_strUrl,string a_strPostData)   {   string strResult ="" ;

   try    {    Encoding encoding = Encoding.GetEncoding("GB2312");

          

    string postData = a_strPostData;

    string strUrl = a_strUrl;

    byte[] data = encoding.GetBytes(postData);

 

    // 准备请求...

    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(strUrl);

    myRequest.Method = "POST";

    myRequest.ContentType="application/x-www-form-urlencoded";

    myRequest.ContentLength = data.Length;

    Stream newStream=myRequest.GetRequestStream();

    // 发送数据

    newStream.Write(data,0,data.Length);    newStream.Close();

    try     {     HttpWebResponse HttpWResp = (HttpWebResponse)myRequest.GetResponse();

     Stream myStream = HttpWResp.GetResponseStream() ;      StreamReader sr = new StreamReader(myStream , Encoding.Default);      StringBuilder strBuilder = new StringBuilder();      while (-1 != sr.Peek())      {      strBuilder.Append(sr.ReadLine());      }

     strResult = strBuilder.ToString();     }     catch(Exception exp)     {        strResult = "错误:" + exp.Message ;     }

   }    catch(Exception exp)    {      strResult = "错误:" + exp.Message ;        }