using System;
using System.Linq;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

/// <summary>
/// 后台读取网页类,使用WebRequest对象
/// </summary>
public class RemoteWeb
{

/// <summary>
/// WebRequestPOST方式读取远程数据
/// </summary>
/// <param name="_url">远程请求地址,需要加参数。</param>
/// <param name="_remoteEncoding">远程编码</param>
/// <returns>编码为UTF-8的字符串</returns>
public static string Post(string _url, Encoding _remoteEncoding)
{

// 发送数据
Encoding utf8 = System.Text.Encoding.UTF8;

byte[] a = utf8.GetBytes(_url.Split('?')[1]);
byte[] data = Encoding.Convert(utf8, _remoteEncoding, a);
if (_remoteEncoding == System.Text.Encoding.UTF8)
{
data = null;
data = a;
}
//byte[] data = _remoteEncoding.GetBytes(_url.Split('?')[1]);

//System.IO.File.WriteAllText(@"e:\temp\ali2.txt", utf8.GetString(data));

Uri url = new Uri(_url.Split('?')[0]);
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
//设置超时

/* 财付通证书 */
//X509Store store = new X509Store("Root", StoreLocation.LocalMachine);
//store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
//X509Certificate2 cer = store.Certificates.Find(X509FindType.FindBySubjectName, "1204816901", false)[0];

//验证服务器证书回调自动验证 SSL
if (_url.Split('?')[0].Substring(0, 5) == "https")
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteWeb.CheckValidationResult);
}
// 证书
if (_url.Split('?')[0].Substring(0, 5) == "https" && _url.Split('?')[0].IndexOf("tenpay.com") != -1)
{
req.ClientCertificates.Add(new X509Certificate2("e:/webroot/cer/1204816901_20100716110715.pfx", "1204816901"));
}

req.Timeout = 30000;
req.AllowAutoRedirect = true;
req.KeepAlive = true;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
//req.EnableSsl = true;
Stream stream = req.GetRequestStream();

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

HttpWebResponse rep = req.GetResponse() as HttpWebResponse;
Stream receiveStream = rep.GetResponseStream();// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, _remoteEncoding);

Char[] read = new Char[256];
int count = readStream.Read(read, 0, 256);
StringBuilder sb = new StringBuilder("");
while (count > 0)
{
String readstr = new String(read, 0, count);
sb.Append(readstr);
count = readStream.Read(read, 0, 256);
}

rep.Close();
receiveStream.Close();
readStream.Close();
req = null;
stream = null;
receiveStream = null;

byte[] c = _remoteEncoding.GetBytes(sb.ToString());
byte[] d = Encoding.Convert(_remoteEncoding, utf8, c);
return utf8.GetString(d);
}

/// <summary>
/// WebRequestPOST方式读取远程数据(GB2312专用)
/// </summary>
/// <param name="_url">远程请求地址,需要加参数。</param>
/// <returns>编码为UTF-8的字符串</returns>
public static string PostGB2312(string _url)
{

// 发送数据
Encoding utf8 = System.Text.Encoding.UTF8;

byte[] data = System.Text.Encoding.GetEncoding("gb2312").GetBytes(_url.Split('?')[1]);

//System.IO.File.WriteAllText(@"e:\temp\ali2.txt", utf8.GetString(data));

Uri url = new Uri(_url.Split('?')[0]);
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
//设置超时

/* 财付通证书 */
//X509Store store = new X509Store("Root", StoreLocation.LocalMachine);
//store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
//X509Certificate2 cer = store.Certificates.Find(X509FindType.FindBySubjectName, "1204816901", false)[0];

//验证服务器证书回调自动验证 SSL
if (_url.Split('?')[0].Substring(0, 5) == "https")
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteWeb.CheckValidationResult);
}

if (_url.Split('?')[0].Substring(0, 5) == "https" && _url.Split('?')[0].IndexOf("tenpay.com") != -1)
{
req.ClientCertificates.Add(new X509Certificate2("e:/webroot/cer/1204816901_20100716110715.pfx", "1204816901"));
}

req.Timeout = 30000;
req.AllowAutoRedirect = true;
req.KeepAlive = true;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
//req.EnableSsl = true;
Stream stream = req.GetRequestStream();

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

HttpWebResponse rep = req.GetResponse() as HttpWebResponse;
Stream receiveStream = rep.GetResponseStream();// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.GetEncoding("gb2312"));

Char[] read = new Char[256];
int count = readStream.Read(read, 0, 256);
StringBuilder sb = new StringBuilder("");
while (count > 0)
{
String readstr = new String(read, 0, count);
sb.Append(readstr);
count = readStream.Read(read, 0, 256);
}

rep.Close();
receiveStream.Close();
readStream.Close();
req = null;
stream = null;
receiveStream = null;

byte[] c = System.Text.Encoding.GetEncoding("gb2312").GetBytes(sb.ToString());
byte[] d = Encoding.Convert(System.Text.Encoding.GetEncoding("gb2312"), utf8, c);
return utf8.GetString(d);
}

/// <summary>
/// WebRequestPOST方式读取远程数据(GBK专用)
/// </summary>
/// <param name="_url">远程请求地址,需要加参数。</param>
/// <returns>编码为UTF-8的字符串</returns>
public static string PostGBK(string _url)
{

// 发送数据
Encoding utf8 = System.Text.Encoding.UTF8;

byte[] data = System.Text.Encoding.GetEncoding("GBK").GetBytes(_url.Split('?')[1]);

//System.IO.File.WriteAllText(@"e:\temp\ali2.txt", utf8.GetString(data));

Uri url = new Uri(_url.Split('?')[0]);
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
//设置超时

/* 财付通证书 */
//X509Store store = new X509Store("Root", StoreLocation.LocalMachine);
//store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
//X509Certificate2 cer = store.Certificates.Find(X509FindType.FindBySubjectName, "1204816901", false)[0];

//验证服务器证书回调自动验证 SSL
if (_url.Split('?')[0].Substring(0, 5) == "https")
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteWeb.CheckValidationResult);
}

if (_url.Split('?')[0].Substring(0, 5) == "https" && _url.Split('?')[0].IndexOf("tenpay.com") != -1)
{
req.ClientCertificates.Add(new X509Certificate2("e:/webroot/cer/1204816901_20100716110715.pfx", "1204816901"));
}

req.Timeout = 30000;
req.AllowAutoRedirect = true;
req.KeepAlive = true;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
//req.EnableSsl = true;
Stream stream = req.GetRequestStream();

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

HttpWebResponse rep = req.GetResponse() as HttpWebResponse;
Stream receiveStream = rep.GetResponseStream();// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.GetEncoding("gb2312"));

Char[] read = new Char[256];
int count = readStream.Read(read, 0, 256);
StringBuilder sb = new StringBuilder("");
while (count > 0)
{
String readstr = new String(read, 0, count);
sb.Append(readstr);
count = readStream.Read(read, 0, 256);
}

rep.Close();
receiveStream.Close();
readStream.Close();
req = null;
stream = null;
receiveStream = null;

byte[] c = System.Text.Encoding.GetEncoding("GBK").GetBytes(sb.ToString());
byte[] d = Encoding.Convert(System.Text.Encoding.GetEncoding("GBK"), utf8, c);
return utf8.GetString(d);
}

public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{ // Always accept
return true;
}

/// <summary>
/// WebRequestGET方式读取远程数据,默认超时30秒
/// </summary>
/// <param name="_url">远程请求地址,需要加参数。无参数可随意加一个。</param>
/// <param name="_remoteEncoding">远程编码</param>
/// <returns>编码为UTF-8的字符串</returns>
public static string GET(string _url, Encoding _remoteEncoding)
{
return GET(_url, _remoteEncoding, 30000);
}

/// <summary>
/// WebRequestGET方式读取远程数据,自定超时时间
/// </summary>
/// <param name="_url">远程请求地址,需要加参数。无参数可随意加一个。</param>
/// <param name="_remoteEncoding">远程编码</param>
/// <param name="_Timeout">超时秒数</param>
/// <returns>编码为UTF-8的字符串</returns>
public static string GET(string _url, Encoding _remoteEncoding, int _Timeout)
{
Encoding utf8 = System.Text.Encoding.UTF8;

//设置超时
HttpWebRequest req;
req = (HttpWebRequest)WebRequest.Create(_url);

req.Timeout = _Timeout;
req.Method = "GET";
req.ContentType = "application/x-www-form-urlencoded";

HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
Stream receiveStream = rep.GetResponseStream();// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, _remoteEncoding);

Char[] read = new Char[256];
int count = readStream.Read(read, 0, 256);
//Common.WriteTXT(@"e:\webroot\errors\length.txt", readStream.ReadToEnd().ToString());
StringBuilder sb = new StringBuilder("");
while (count > 0)
{
String readstr = new String(read, 0, count);
sb.Append(readstr);
count = readStream.Read(read, 0, 256);
}

rep.Close();
receiveStream.Close();
readStream.Close();
req = null;
receiveStream = null;

byte[] c = _remoteEncoding.GetBytes(sb.ToString());
byte[] d = Encoding.Convert(_remoteEncoding, utf8, c);
return utf8.GetString(d);
}
}

HttpWebRequest后台读取网页类的更多相关文章

  1. 正则表达式相关:C# 抓取网页类(获取网页中所有信息)

    类的代码: using System; using System.Data; using System.Configuration; using System.Net; using System.IO ...

  2. [转]正则表达式相关:C# 抓取网页类(获取网页中所有信息)

    using System; using System.Data; using System.Configuration; using System.Net; using System.IO; usin ...

  3. 利用backgroundwork----递归读取网页源代码,并下载href链接中的文件

    今天闲着没事,研究了一下在线更新程序版本的问题.也是工作中的需要,开始不知道如何下手,各种百度也没有找到自己想要的,因为我的需求比较简单,所以就自己琢磨了一下.讲讲我的需求吧.自己在IIs上发布了一个 ...

  4. struts2中从后台读取数据到<s:select>

    看到网上好多有struts2中从后台读取数据到<s:select>的,但都 不太详细,可能是我自己理解不了吧!所以我自己做了 一个,其中可能 有很多不好的地方,望广大网友指出 结果如图 p ...

  5. php 读取网页源码 , 导出成txt文件, 读取xls,读取文件夹下的所有文件的文件名

    <?php // 读取网页源码$curl = curl_init();curl_setopt($curl, CURLOPT_URL, $url);curl_setopt($curl, CURLO ...

  6. Ajax的post方法,模拟 从后台读取数据小demo

    $(document).ready(function() { //定义一个函数 function timer() { $.post("1.json", function(data, ...

  7. excel读取 工具类

    package cn.yongche.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOExce ...

  8. C#读取网页源码

    #region 1.读取 网页源码 + static string ReadHtml(string urlStr,int type) /// <summary> /// 读取 网页源码 + ...

  9. Utils--前台调用后台接口工具类

    Utils--前台调用后台接口工具类 package com.taotao.manage.httpclient; import java.io.IOException; import java.net ...

随机推荐

  1. Linux c实现服务端与客户端聊天

    主要利用socket通信实现,具体代码如下 客户端: #include <stdio.h> #include <stdlib.h> #include <string.h& ...

  2. 【WEB前端经验之谈】没有速成,只有不断积累。

    2013年8月25日,我人生中的第一份正式工作开始了,第一份工作做的是当时学习的asp.net,用的是C#语言. 到第一家公司上班是公司是做一个OA系统,不过我去的时候大部分都已经完成了,剩下的都是细 ...

  3. [渣翻译] 在ASP.NET MVC WebAPI项目中使用 AngularJS

    原文地址http://blog.technovert.com/2013/12/setting-up-angularjs-for-asp-net-mvc-n-webapi-project/ 我们最近发布 ...

  4. Android--按钮点击事件

    Android中Button的点击事件非常简单,主要是一个内部类的问题 在界面上存在两个按钮和一个文本框,点击不同按钮的时候文本框中显示不同按钮的文字信息 <?xml version=" ...

  5. jQuery UI dialog

    初始化参数 对于 dialog 来说,首先需要进行初始化,在调用 dialog 函数的时候,如果没有传递参数,或者传递了一个对象,那么就表示在初始化一个对话框. 没有参数,表示按照默认的设置初始化对话 ...

  6. 3、面向对象以及winform的简单运用(类的初步认识)

    什么是类? “类”是面向对象编程的基本单元,一个类一般包含两种成员:字段和方法——即变量和函数. 例: //字段或变量的定义 public int age; //方法或函数的定义 public int ...

  7. WCF 入门(25,26,27,28)

    前言 项目赶时间,工期紧,熬过这段时间应该就好了吧.希望如此. 今天把自己那部分写的差不多了,回来和小伙伴一起又看了一遍<夏洛特烦恼>,还挺好看的,明天继续加班,do it. 第25-28 ...

  8. ECMAScript —— 学习笔记(思维导图版)

    导图

  9. 让js的forin循环禁止forin到某个属性的话要怎么做

    //知识点1:for In循环是可以枚举到继承的属性的://知识点2:使用defineProperty让属性无法通过forIn枚举到://知识点3:用definedProperty重新定义一个属性药把 ...

  10. poj3468 splay(成段跟新 区间求和)

    用splay做了一遍. 建树时是按照数列序号从小到大排好的,每个节点左子树的序号小于右子树的序号及这个节点本身.由于查询[l,r]要伸展l-1,r+1所以我们要多加2个结点,保证边界处理时不出问题.由 ...