經常使用 Http 的請求方法

第一次用markdown寫博客,體驗下

由於經常使用Http的幾種請求方式,總結一下。

1.封裝兩個Http的最經常使用方法,叫作HttpHelper類。html

HttpPost:json

public static string HttpPost(string Url, string postDataStr)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postDataStr.Length;

        StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
        writer.Write(postDataStr);
        writer.Flush();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        string encoding = response.ContentEncoding;

        if (encoding == null || encoding.Length < 1)
        {
            encoding = "UTF-8"; //默認編碼  
        }
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
        string retString = reader.ReadToEnd();
        return retString;
    }

HttpGet:markdown

public static string HttpGet(string Url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "GET";
        request.ContentType = "text/html;charset=UTF-8";

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();

        return retString;
    }

WebClientde中Post和Get:app

//Post
    using (var client = new WebClient())
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/json";
        client.Encoding = Encoding.UTF8;
        result = client.UploadString(postUrl, "POST", postData);
    }
    //Get 
    var wc = new WebClient();
    var jsonResult = wc.DownloadString(Url);

封裝好Http的方法,直接傳入Url和postData便可,沒必要每次建立request對象。post

更新:the remote server returned an error (401) unauthorized編碼

var req = (HttpWebRequest)WebRequest.Create(tgtUrl);
    req.UseDefaultCredentials = true;
    req.PreAuthenticate = true;
    req.Credentials = CredentialCache.DefaultCredentials;
    var response = req.GetResponse();
    var stream = req.GetRequestStream();

    var wc = new WebClient();
    //Set default credential, avoid unauthorize error
    wc.Credentials = CredentialCache.DefaultCredentials;
    wc.UseDefaultCredentials = true;
相關文章
相關標籤/搜索