Analytics

2016年9月7日 星期三

[HttpWebRequest]使用 HttpWebRequest 下載/呼叫API (Use HttpWebRequest download / Call API)


問題
使用 HttpWebRequest 下載/呼叫API



解決方法
Code
public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
{
    var property = typeof(WebHeaderCollection).GetProperty("InnerCollection",
        System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
    if (property != null)
    {
        var collection = property.GetValue(header, null) as NameValueCollection;
        collection[name] = value;
    }
}

public static Stream getHttpWebResponse(string traget, WebProxy webProxy, int timeOut)
{
    return getHttpWebResponse(traget, webProxy, timeOut, null);
}

public static Stream getHttpWebResponse(string traget, WebProxy webProxy, int timeOut, Dictionary<string, string> headerInfo)
{
    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
    HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(traget);

    httpRequest.Method = WebRequestMethods.Http.Get;
    if (webProxy != null)
    {
        httpRequest.Timeout = timeOut;
        httpRequest.Proxy = webProxy;
        webProxy.BypassProxyOnLocal = false;
    }

    if (headerInfo != null)
    {
        foreach (KeyValuePair<string, string> pair in headerInfo)
        {
            SetHeaderValue(httpRequest.Headers, pair.Key, pair.Value);
        }
    }

    HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
    Stream httpResponseStream = httpResponse.GetResponseStream();
    return httpResponseStream;
}

public static string getStream2String(Stream httpResponseStream, Encoding encoding)
{
    using (var reader = new StreamReader(httpResponseStream, encoding))
    {
        string content = reader.ReadToEnd();
        return content;
    }
}

使用方式
Stream httpResponseStream = getHttpWebResponse(traget, null, 5000);
string content= getStream2String(httpResponseStream, Encoding.UTF8);

沒有留言:

熱門文章