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看不到异常的具体原因 }
|