码迷,mamicode.com
首页 > Windows程序 > 详细

C# 发送HttpWebRequest和HttpWebResponse流读取方式及异常信息获取

时间:2019-03-15 17:26:37      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:uri   rev   poi   gets   end   utf-8   eth   post   ret   

try
{
    Uri uri = new Uri(url);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "post"; //post、get
    request.Headers.Add("Authorization", "APPCODE " + appcode);//具体情况而定
    request.ProtocolVersion = HttpVersion.Version11;
    request.ContentType = "application/json; charset=UTF-8";
    request.KeepAlive = false;

    //request.Credentials = CredentialCache.DefaultCredentials;
    //request.Referer = url;
    //request.MaximumAutomaticRedirections = 4;
    //request.MaximumResponseHeadersLength = 4;
    //ServicePointManager.DefaultConnectionLimit = 100;
    //ServicePointManager.CheckCertificateRevocationList = true;

    //post提交的数据(data)
    byte[] byteRequest = Encoding.UTF8.GetBytes(data);
    Stream rs = request.GetRequestStream();
    rs.Write(byteRequest, 0, byteRequest.Length);
    rs.Close();

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream resultStream = response.GetResponseStream();


    //接收流两种方式
1.
    MemoryStream ms = new MemoryStream();
    byte[] buffer = new byte[1024];
    while (true)
    {
        int sz = resultStream.Read(buffer, 0, 1024);
        if (sz == 0) break;
        ms.Write(buffer, 0, sz);
    }
    string content = Encoding.UTF8.GetString(ms.ToArray());
    //如是图片
    //System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

2.
    StreamReader sr = new StreamReader(resultStream, Encoding.UTF8);
    string html = sr.ReadToEnd();

    sr.Close();
    resultStream.Close();
    request.Abort();
    response.Close();
    return html;
}
catch (WebException ex)
{
    HttpWebResponse res = (HttpWebResponse)ex.Response;
    Stream myResponseStream = res.GetResponseStream();
    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
    string retString = myStreamReader.ReadToEnd();

    //retString 可以看到异常的具体原因,而ex看不到异常的具体原因
}

 

C# 发送HttpWebRequest和HttpWebResponse流读取方式及异常信息获取

标签:uri   rev   poi   gets   end   utf-8   eth   post   ret   

原文地址:https://www.cnblogs.com/liushuixiying/p/10538248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!