文件下载
断点续传http://www.iwms.net/n1664c13.aspx
验证码
图片验证码的类修改说明:
1,对源代码做了部分算法优化;
2,对图像输出做了优化;
3,对图像的反识别做了优化;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifusing System;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifusing System.Collections.Generic;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifusing System.Text;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifusing System.Web;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifusing System.Drawing;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifnamespace Common
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif{
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif /// <summary>
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif /// 验证码模块
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif /// </summary>
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif public class CreateImage
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif {
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif public static void DrawImage()
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif {
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif HttpContext.Current.Response.Clear();
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif CreateImage img = new CreateImage();
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif HttpContext.Current.Session["CheckCode"] = img.RndNum(3);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif img.CreateImages(HttpContext.Current.Session["CheckCode"].ToString());
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif HttpContext.Current.Response.End();
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif }
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif /// <summary>
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif /// 生成验证图片
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif /// </summary>
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif /// <param name="checkCode">验证字符</param>
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif private void CreateImages(string checkCode)
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif {
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif int iwidth = (int)(checkCode.Length * 13);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif Graphics g = Graphics.FromImage(image);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif g.Clear(Color.White);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif //定义颜色
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif //定义字体
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif Random rand = new Random();
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif //输出不同字体和颜色的验证码字符
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif for (int i = 0; i < checkCode.Length; i++)
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif {
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif int cindex = rand.Next(7);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif int findex = rand.Next(5);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif Font f;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif int k=rand.Next(3);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif if ( k== 1){ f = new System.Drawing.Font(font, 13, FontStyle.Bold); }
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif else if (k == 2) {f = new System.Drawing.Font(font, 13, FontStyle.Bold | FontStyle.Strikeout); }
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif else { f = new System.Drawing.Font(font, 13, FontStyle.Bold | FontStyle.Italic); };
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif Brush b = new System.Drawing.SolidBrush(c);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif g.DrawString(checkCode.Substring(i, 1), f, b, (i * 12), rand.Next(2));
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif }
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif //画一个边框
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif //随机输出噪点
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif for (int i = 0; i < 50; i++)
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif {
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif int x = rand.Next(image.Width);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif int y = rand.Next(image.Height);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif float x1, y1;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif x1 = 0.5F;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif y1 = 0.5F;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, x1, y1);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif }
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif //输出到浏览器
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif HttpContext.Current.Response.ClearContent();
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif HttpContext.Current.Response.ContentType = "image/Jpeg";
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif image.Save(HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif g.Dispose();
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif image.Dispose();
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif }
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif /// <summary>
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif /// 生成随机的字母
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif /// </summary>
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif /// <param name="VcodeNum">生成字母的个数</param>
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif /// <returns>string</returns>
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif private string RndNum(int VcodeNum)
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif {
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif //采用一个简单的算法以保证生成随机数的不同
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif Random rand = new Random();
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif int min=(int)Math.Pow(10, VcodeNum);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif int max=(int)(Math.Pow(10, VcodeNum + 1) - 1);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif return rand.Next(min, max).ToString();
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif }
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif }
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif}
推荐一个图片验证码网站不错的。
http://www.lafdc.com/captcha/
[ 本帖最后由 faunus 于 2008-10-24 21:03 编辑 ]
待查
http://topic.csdn.net/u/20070811 ... d-5e6428e09957.htmlhttp://blog.csdn.net/net_lover/archive/2006/10/12/1332065.aspx
[ 本帖最后由 faunus 于 2008-11-3 20:44 编辑 ]
BASE64
Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,在发送电子邮件时,服务器认证的用户名和密码需要用Base64编码,附件也需要用Base64编码。下面简单介绍Base64算法的原理,由于代码太长就不在此贴出
Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。
Base64要求把每三个8Bit的字节转换为四个6Bit的字节(3*8 = 4*6 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3。
这样说会不会太抽象了?不怕,我们来看一个例子:
转换前 aaaaaabb ccccdddd eeffffff
转换后 00aaaaaa 00bbcccc 00ddddee 00ffffff
应该很清楚了吧?上面的三个字节是原文,下面的四个字节是转换后的Base64编码,其前两位均为0。
转换后,我们用一个码表来得到我们想要的字符串(也就是最终的Base64编码),这个表是这样的:(摘自RFC2045)
Table 1: The Base64 Alphabet
Value EncodingValue EncodingValue EncodingValue Encoding
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v
14 O 31 f 48 w (pad) =
15 P 32 g 49 x
16 Q 33 h 50 y
让我们再来看一个实际的例子,加深印象!
转换前 10101101 10111010 01110110
转换后 00101011 00011011 00101001 00110110
十进制 43 27 41 54
对应码表中的值 r b p 2
所以上面的24位编码,编码后的Base64值为 rbp2
解码同理,把 rbq2 的二进制位连接上再重组得到三个8位值,得出原码。
(解码只是编码的逆过程,在此我就不多说了,另外有关MIME的RFC还是有很多的,如果需要详细情况请自行查找。)
用更接近于编程的思维来说,编码的过程是这样的:
第一个字符通过右移2位获得第一个目标字符的Base64表位置,根据这个数值取到表上相应的字符,就是第一个目标字符。
然后将第一个字符左移4位加上第二个字符右移4位,即获得第二个目标字符。
再将第二个字符左移2位加上第三个字符右移6位,获得第三个目标字符。
最后取第三个字符的右6位即获得第四个目标字符。
在以上的每一个步骤之后,再把结果与 0x3F 进行 AND 位操作,就可以得到编码后的字符了。
判断网页编码
(1)原始方案System.Text.Encoding.Default
采用当前的默认编码,可以解决大部分问题,但是很多跟情况下同样会出错。
(2)HTTPWebrequest 的CharacterSet(MSND上给的方案,本来应该的做法)
该属性可以返回该网站编码,但是总为空。
(3)老外的解决之道
Sven Groot
I came across a very silly (and annoying) bug in the HttpWebResponse.CharacterSet property. Let's see if you can spot it (code extracted with reflector):
public string get_CharacterSet()
{
this.CheckDisposed();
string text1 = this.m_HttpResponseHeaders.ContentType;
if ((this.m_CharacterSet == null) && !ValidationHelper.IsBlankString(text1))
{
this.m_CharacterSet = string.Empty;
string text2 = text1.ToLower(CultureInfo.InvariantCulture);
if (text2.Trim().StartsWith("text/"))
{
this.m_CharacterSet = "ISO-8859-1";
}
int num1 = text2.IndexOf(";");
if (num1 > 0)
{
while ((num1 = text2.IndexOf("charset", num1)) >= 0)
{
num1 += 7;
if ((text2 == ';') || (text2 == ' '))
{
while ((num1 < text2.Length) && (text2 == ' '))
{
num1++;
}
if ((num1 < (text2.Length - 1)) && (text2 == '='))
{
num1++;
int num2 = text2.IndexOf(';', num1);
if (num2 > num1)
{
this.m_CharacterSet = text1.Substring(num1, num2).Trim();
break;
}
this.m_CharacterSet = text1.Substring(num1).Trim();
break;
}
}
}
}
}
return this.m_CharacterSet;
}
(4)另一种方法(先获取内容,再根据内容来判)
static
string GetHtml(string url, Encoding encoding) { byte[] buf =
new WebClient().DownloadData(url); if (encoding !=
null) return encoding.GetString(buf); string html = Encoding.UTF8.GetString(buf); encoding = GetEncoding(html); if (encoding ==
null
|| encoding == Encoding.UTF8) return html; return encoding.GetString(buf); }
(5)结合3/4的办法(当然去看HttpWebResponse函数的源代码了)
//得到CharacterSet
private
string getEncoding (HttpWebResponse httpResp)
{
string contentType = httpResp.ContentType ;
int i = contentType.IndexOf("charset=");
if (i>=0) { i +=
8;
int j = contentType.IndexOf(';', i);
if (j>=i) {
return contentType.Substring(i,j-i).Trim(); }
return contentType.Substring(i); }
return
string.Empty;}
[ 本帖最后由 faunus 于 2008-10-27 23:13 编辑 ]
高精度计时
利用QueryPerformanceFrequency和QueryPerformanceCountervoid main() {
LARGE_INTEGER lv;
// 获取每秒多少CPU Performance Tick
QueryPerformanceFrequency( &lv );
// 转换为每个Tick多少秒
double secondsPerTick = 1.0 / lv.QuadPart;
for ( size_t i = 0; i < 100; ++i ) {
// 获取CPU运行到现在的Tick数
QueryPerformanceCounter( &lv );
// 计算CPU运行到现在的时间
// 比GetTickCount和timeGetTime更加精确
double timeElapsedTotal = secondsPerTick * lv.QuadPart;
cout.precision( 6 );
cout << fixed << showpoint << timeElapsedTotal << endl;
//printf( "%lf \n", timeElapsedTotal ) ;
}
}
Charset
Charset 和 Encoding 的区别http://www.cftea.com/c/2008/01/LG3YPDRZSTHTJ2IH.asp
Character Set Recognition 字符集识别
http://www.yesky.com/imagesnew/software/css/css2/z_charset.html
简单型的
http://www.jb51.net/article/15764.htm
浏览器
http://hi.baidu.com/19www/blog/item/2d6c9fc6e4a4631d9d163db2.html
浏览器判别顺序:
IE解析网页编码时:HTML内的标签优先,而后才是HTTP header内的讯息;
Mozilla、Mozilla Firefox、Sarafi系列的浏览器:则刚刚相反,HTTP header内的讯息优先,然后是HTML内的标签。UTF-8为3个字节表示一个汉子,而普通的GB2312或BIG5是两个。页面输出时,由于上述原因,使浏览器解析、输出<title></title>的内容时,如果在</title>前有奇数个全角字符时,IE把UTF-8当作两个字节解析时出现半个汉字的情况,这时该半个汉字会和</title>的<结合成一个乱码字,导致IE无法读完<title>部分,使整个页面为空百输出。而这个时候如果察看源文件的话,会发现实际上整个叶面全部已经输出了。
因此最简单的解决办法是再网页文件的<head></head>标签中一定要把字符定义<meta http-equiv="Content-Type" c /> 放在<title></title>之前.
根据http协议和html的规范,有3种办法可以得到一个页面的字符编码:
1. An HTTP "charset" parameter in a "Content-Type" field.
example:
Content-Type: text/html; charset=EUC-JP
2. A META declaration with "http-equiv" set to "Content-Type" and a value set for "charset".
example:
<META http-equiv="Content-Type" c>
3. The charset attribute set on an element that designates an external resource.
example:
<A href="http://www.w3.org/" charset="ISO-8859-1">W3C Web site</A>
第一个很少有人会设置,所以,没有默认编码的说法。一般的说,如果第一个没有说明编码的话,必须在后2者中说明编码,这样做的首要条件是:在html的编码中,ascii码仍然可以识别。这样的语言如gb2312,因为英文字符仍然保存为单个字节,和ascii码一样。
unicode-16的识别:
UTF-16使用上述规则无法识别(但是,UTF-8可以),所以,它的识别规则比较特殊。如果一个传输过来的文本,第一个和第二个字节为0xff和0xfe的话(这2个字节的顺序说明了utf-16编码是否是大头在前的),就表明从第三个字节开始,这个文档是使用了UTF-16编码。其识别的处理应该在上述识别方法的前面进行。
Unicode-8的识别:
utf-8以0xef, 0xbb, 0xbf开头,所以,遇到这3个字节的时候,应该可以肯定的说,余下来的字符流是utf-8编码。
[ 本帖最后由 faunus 于 2008-11-1 21:12 编辑 ]
专链转换原理分析
首先要搞懂base64编码,网上有一篇很好的入门教程,地址:http://www.luocong.com/articles/show_article.asp?Article_ID=17搞懂了base64编码一切都简单了,下面以实例讲解转换过程。例如华军winrar 3.71的下载地址是
http://p2s.newhua.com/down/wrar371sc.exe
1、普通地址转换为迅雷地址
在原地址前面加"AA",后面加"ZZ"(注:不包括引号),地址变为
AAhttp://p2s.newhua.com/down/wrar371sc.exeZZ
此地址base64编码为
QUFodHRwOi8vcDJzLm5ld2h1YS5jb20vZG93bi93cmFyMzcxc2MuZXhlWlo=
迅雷专链即在上地址前加thunder://,即
thunder://QUFodHRwOi8vcDJzLm5ld2h1YS5jb20vZG93bi93cmFyMzcxc2MuZXhlWlo=
2、普通地址转换为快车地址
在原地址前后都加上""(注:不包括引号),地址变为
http://p2s.newhua.com/down/wrar371sc.exe
此地址base64编码为
W0ZMQVNIR0VUXWh0dHA6Ly9wMnMubmV3aHVhLmNvbS9kb3duL3dyYXIzNzFzYy5leGVbRkxBU0hHRVRd
快车专链即在上地址前加flashget://,注意后面还要加上"&符号",符号怎么得出我也不清楚,我自己在最后后面加的是我个人信息,至今未有人报告转换错误,即
Flashget://W0ZMQVNIR0VUXWh0dHA6Ly9wMnMubmV3aHVhLmNvbS9kb3duL3dyYXIzNzFzYy5leGVbRkxBU0hHRVRd&yinbing1986
3、普通地址转换为旋风地址
旋风相对就简单多了,将原地址直接base64编码为
aHR0cDovL3Aycy5uZXdodWEuY29tL2Rvd24vd3JhcjM3MXNjLmV4ZQ==
旋风专链即在上地址前加qqdl://,即
qqdl://aHR0cDovL3Aycy5uZXdodWEuY29tL2Rvd24vd3JhcjM3MXNjLmV4ZQ==
NChardet 专题
一、什么是NChardetNChardet是mozilla自动字符编码识别程序库chardet的.NET实现,它移植自jchardet,chardet的java版实现,可实现对给定字符流的编码探测。
二、NChardet是如何工作
NChardet通过逐个比较输入字符来猜测编码;由于是猜测,所以可能会有不能完全识别的情况;如果输入字符不能确定正确的编码,那么NChardet会给出一组可能的编码值。
三、如何使用NChardet
要使用NChardet来探测编码,需要进行如下步骤。
1、使用制定的语言线索来构造Detector类的实例对象。
2、用实现了ICharsetDetectionObserver接口的对象作为参数来调用Detector类的Init方法。
3、传入要探测的字符流进行编码探测。
4、调用Detector类的DataEnd方法。
5、得到结果或可能的结果集。
四、语言线索
语言线索是一个整数,可用的语言线索有如下几个:
1. Japanese
2. Chinese
3. Simplified Chinese
4. Traditional Chinese
5. Korean
6. Dont know (默认)
五、调用方法
ICharsetDetectionObserver接口只有一个Notify方法,当NChardet引擎认为自己已经探测出正确的编码时,它就会调用这个Notify方法,用户程序可以从这个Nodify方法中得到通知(重写ICharsetDetectionObserver接口的Notify实现)。
六、其它
IE里面的mlang.dll能实现相同的功能。
[ 本帖最后由 faunus 于 2008-11-1 21:42 编辑 ]
SSL
目的:对于用HttpWebRequest加载证书请求远端https服务器时,发生的
“基础连接已经关闭: 无法与远程服务器建立信任关系。”/
“The underlying connection was closed. Could not establish a secure SSL/TLS connection”错误,我们可以用如下方式解决。
重现:
使用以下代码,你就可以得到这个错误“基础连接已经关闭: 无法与远程服务器建立信任关系”:
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Web.Services2.Security;
using Microsoft.Web.Services2.Security.Tokens;
using Microsoft.Web.Services2.Security.X509;
static void Main(string[] args)
{
StringBuilder sb=new StringBuilder();
string _strToRequest = "send";
try
{
//POST请求开始
byte[] bt=Encoding.Default.GetBytes("send");
HttpWebRequest Req=(HttpWebRequest)System.Net.WebRequest.Create("https://202.108.CCC.XXX:Port//");
Req.KeepAlive=true;
//Req.Timeout=60000;
Req.C;
Req.ContentLength=_strToRequest.Length;
Req.Method="POST";
X509CertificateStore store = X509CertificateStore.CurrentUserStore( X509CertificateStore.MyStore );
store.OpenRead();
//读取证书的keyid
Microsoft.Web.Services2.Security.X509.X509CertificateCollection certs =
store.FindCertificateByKeyIdentifier( Convert.FromBase64String( "CXv+xZ78zI3qWHGJ6Wh9BF6B23A=" ) );
X509SecurityToken token = null;
if (certs.Count > 0)
{
// 得到证书存储区的第1个人证书
token = new X509SecurityToken( ((Microsoft.Web.Services2.Security.X509.X509Certificate) certs) );
}
if(token != null)
Req.ClientCertificates.Add(token.Certificate);
Req.KeepAlive=true;
Stream ReqStream=Req.GetRequestStream();
ReqStream.Write(bt,0,bt.Length);
ReqStream.Close();
//得到响应
HttpWebResponse res=(HttpWebResponse)Req.GetResponse();
StreamReader sr=new StreamReader(res.GetResponseStream(),Encoding.Default);
sb.Append(sr.ReadToEnd());
res.Close();
sr.Close();
}
catch(Exception ex)
{
sb.Remove(0,sb.Length);
sb.Append("<?xml version=\"1.0\" encoding=\"gb2312\"?>\n");
sb.Append("<slia ver=\"1.0.0\">\n");
sb.Append("<result resid=\"501\">"+ex.Message+"</result>\n");
sb.Append("</slia>\n");
}
Console.WriteLine(sb.ToString());
Console.Read();
}
原因:
证书标识特定的计算机,该计算机的名称位于证书的公共名称中。但是,很容易就会更改计算机的名称或使用客户端配置文件中的“localhost”,这会在客户端和服务器证书中的公共名称之间造成不匹配的情况。在 .NET Framework 1.0 版中,这一不匹配的情况将被忽略,并且将在服务器上引发调用。
从 .NET Framework 1.1 版开始,这一不匹配的情况会引发以下异常:“System.Net.WebException:基础连接已经关闭:无法与远程服务器建立信任关系”。如果您无法配置远程处理客户端以使用证书公共名称,则可以使用客户端应用程序配置文件中的以下设置重写这一不匹配的情况。
<system.net>
<settings>
<servicePointManager
checkCertificateName="true"
/>
</settings>
</system.net>
若要以编程方式使客户端忽略证书名称不匹配,客户端必须创建一个特定类的实例,如果 certificateProblem 值为 0x800c010f,该类将实现 ICertificatePolicy 接口并实现 CheckValidationResult 方法以返回 true。然后,您必须将该对象注册到 System.Net.ServicePointManager 对象,方法是将该对象传递到 ServicePointManager.CertificatePolicy 属性。”
解决之道:
但是用它列出的代码还是不对,我们改为CheckValidationResult无条件返回true即可。如下所示声明一个TrustAllCertificatePolicy类:
public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
public TrustAllCertificatePolicy()
{}
public bool CheckValidationResult(ServicePoint sp,
System.Security.Cryptography.X509Certificates.X509Certificate cert,
WebRequest req, int problem)
{
return true;
}
}
然后,在请求之前加上
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
即可。
这样,代码就可以顺利和https服务器建立SSL通道了。
参考MSND(关键)
http://msdn.microsoft.com/en-us/library/y0hedwet.aspx
[ 本帖最后由 faunus 于 2008-11-1 21:51 编辑 ]