异步操作,所以想用这个机会搞一下。就看了一下。
这一看不要紧,搞得我一头雾水。上网上去问,大家给出的方法都是用多线程来搞定。这个在下一个帖子中我会发上来。这里主要说一下用BeginGetResponse,EndGetResponse来完成 异步操作。
先说一下,我的要求:
一,从数据库中取出所有的IP
二,利用 httpwebrequest的post方法在网上取得它的相应地址。当然了,是用post还是用get主要是看网上的网站是用什么方法来传值。
三,将所得到的值写入数据库

下面我把我的代码放上来,前台没有什么东西,运行的结果是直接写入数据库,
数据库名为DBCT_Dev
省份表S_Province,其中ProvinceName为省分名。ProvinceCode为省分相对的Code
市级表S_City,其中CityName为市名。ZipCode为市相对应的Code。
这二个表是在网上找到的,有很多中国省市关联表,大家可以去下一个。
用户IP表UserCode,其中Code为其IP所对应的省市Code,IP为用户的IP地址。

好了,下面是代码

1. using
2. using
3. using
4. using
5. using
6. using
7. using
8. using
9. using
10. using
11. using
12. using
13. 
14. namespace
15. {

16. public partial class
17.     {

18. public DBClass db = new DBClass();//我自己写的一个类,主要是用来做一些数据库操作的,你可以使用你自己的
19. 
20. public static Hashtable ht = new
21. 
22. private static ManualResetEvent allDone = new ManualResetEvent(false);
23. 
24. public static string
25. 
26. protected void Page_Load(object
27.         {

28. if
29.             {

30. 
31. //将数据库中Code为空ip不为空的记录存入,放到一个DataTable中。
32. string strsql = "select * from UserCode where UserIP<>'' and (Code is null or code = '')";
33.                 
34. 
35.                 DataTable dt = db.GetDataTable(strsql);
36. 
37. 
38. for (int
39.                 {

40. //调用转化方法
41. "id"].ToString());
42. 
43. 
44. //每次调用间隔一秒,通过实验得到,如果你的数据量大,最好间隔5秒
45.                     Thread.Sleep(1000);
46.                 }
47. 
48.                 Thread.Sleep(5000);
49. 
50.                 dt.Dispose();
51. 
52. //调用将转化信息存入数据库的方法
53.                 ChangeUserCode();
54.             }
55.         }
56. 
57. public void getPost(string
58.         {

59. //定义变量
60. //singleid 传入的用户信息ID
61. //singleip 根据用户信息ID,而取到的IP
62. //strAction post必传值之一
63. //strCode 传入用户信息表中的code值
64. //
65.             singleid = id;
66. 
67. //通过GetSingleValue方法,得到相应的值,这里GetSingleValue(表名,要得到的值,条件语句)
68. string singleip = db.GetSingleValue("UserCode", "UserIP", "id="
69. string strAction = "2";
70. string strCode = "";
71. 
72. 
73. //将得到的post值,转化为byte型
74. new
75. string postData = "ip="
76. "&action="
77. byte[] data = encoding.GetBytes(postData);
78. 
79. //建立HttpWebRequest
80. HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www2.ip138.com/ips8.asp");
81. "POST";
82. "application/x-www-form-urlencoded";
83.             myRequest.ContentLength = data.Length;
84. 
85.             Stream myStream = myRequest.GetRequestStream();
86.             myStream.Write(data, 0, data.Length);
87.             myStream.Close();
88. 
89. //开始调用异步操作
90. new
91. 
92.             allDone.WaitOne();
93.         }
94. 
95. private void
96.         {

97. HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
98. 
99. //Stream postStream = request.EndGetResponse(asynchronousResult);
100. 
101. //异步回调方法使用 EndGetResponse 方法返回实际的 WebResponse。 
102.             HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
103.             Stream streamResponse = response.GetResponseStream();
104. new
105. string
106. //string con = responseString.Substring(responseString.IndexOf(" 本站主数据") + 6, responseString.IndexOf("</li><li>参考数据 一") - responseString.IndexOf("本站主数据") - 1);
107. //Response.Write(con + "<br>");
108. 
109. 
110. //判断是否是有省市的信息,如果信息中有省,市,则进行存入数据库,如为127.0.0.1,是直接给本省code。其它信息,则不给记录
111. string singleip = "";
112. string strCode = "";
113.             
114. if (singleip == "127.0.0.1")
115.             {

116. "0008";
117.             }
118. else
119.             {

120. if (content.IndexOf("省") == -1 && content.IndexOf("市") == -1 && singleid != "127.0.0.1")
121.                 {

122. if (content.IndexOf("查询太频繁") != -1)
123.                     {

124. "查询太频繁";
125.                     }
126. else
127.                     {

128. "0035";
129.                     }
130.                 }
131. else
132.                 {

133. if (content.IndexOf("省") != -1)
134.                     {

135. string con = content.Substring(content.IndexOf("本站主数据") + 6, content.IndexOf("</li><li>参考数据一") - content.IndexOf("本站主数据") - 1);
136. string strpro = con.Substring(0, con.IndexOf("省") + 1);
137. "S_Province", "ProvinceCode", "ProvinceName='" + strpro + "'").Trim();
138. //strCode = strpro;
139.                     }
140. 
141. if (content.IndexOf("市") != -1)
142.                     {

143. string con = content.Substring(content.IndexOf("本站主数据") + 6, content.IndexOf("</li><li>参考数据一") - content.IndexOf("本站主数据") - 1);
144. string strpro = con.Substring(con.IndexOf("省") + 1, con.IndexOf("市") - con.IndexOf("省"));
145. "S_City", "ZipCode", "CityName='" + strpro + "'").Trim(); ;
146.                     }
147.                 }
148. 
149.             }
150. 
151. 
152. if (strCode == "")
153.             {

154. "0035";
155.             }
156. 
157. //将信息存入hashtable
158.             ht.Add(singleid, strCode);
159. 
160. 
161. 
162.             streamResponse.Close();
163.             streamRead.Close();
164. 
165. 
166.             response.Close();
167. 
168. 
169. 
170.             allDone.Set();
171. 
172.         }
173. 
174. 
175. public void
176.         {

177. if
178.             {

179. foreach (DictionaryEntry objDE in
180.                 {

181. string strsql = "update UserCode set Code='" + objDE.Value.ToString() + "' where id=" + objDE.Key.ToString() + "";
182. try
183.                     {

184.                         db.ExecuteSql(strsql);
185.                     }
186. catch
187.                     {

188. continue;
189.                     }
190.                 }
191.             }
192.         }
193. 
194. 
195.     }
196. }

下面的是周公在CSDN上一个帖子上给出的代码是用BeginGetRequestStream,GetResponseStream来完成的

1. using
2. using
3. using
4. using
5. using
6. 
7. class
8. {

9. public static ManualResetEvent allDone = new ManualResetEvent(false);
10. public static void
11.     {

12.         
13. 
14. // Create a new HttpWebRequest
15. HttpWebRequest request=(HttpWebRequest) WebRequest.Create("http://www.contoso.com/example.aspx");    
16.     
17. // Set the ContentType property. 
18. "application/x-www-form-urlencoded";
19. // Set the Method property to 'POST' to post data to the URI.
20. "POST";
21. // Start the asynchronous operation.    
22. new
23.             
24. // Keep the main thread from continuing while the asynchronous
25. // operation completes. A real world application
26. // could do something useful such as updating its user interface. 
27.             allDone.WaitOne();
28. 
29. // Get the response.
30.             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
31.             Stream streamResponse = response.GetResponseStream();
32. new
33. string
34.             Console.WriteLine(responseString);
35. // Close the stream object.
36.             streamResponse.Close();
37.             streamRead.Close();
38.     
39. // Release the HttpWebResponse.
40.             response.Close();
41.         }
42.     
43. private static void
44.     {    
45. HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
46. // End the operation.
47.             Stream postStream = request.EndGetRequestStream(asynchronousResult);
48. "Please enter the input data to be posted:");
49. string
50.             
51. // Convert the string into a byte array.
52. byte[] byteArray = Encoding.UTF8.GetBytes(postData);
53. // Write to the request stream.
54.             postStream.Write(byteArray, 0, postData.Length);
55.             postStream.Close ();
56.             allDone.Set();    
57.     }
58. 
59. }
60. ----------------------------------------------------------------------------------------------------------

C# HttpWebRequest异步

 

----------------------------Un Test-------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;


namespace WebReqHtml
{
    internal class WebReqState
    {
        public byte[] Buffer;
        public MemoryStream ms;
        public const int BufferSize = 1024;
        public Stream OrginalStream;
        public HttpWebResponse WebResponse;
    
        public WebReqState()
        {
            Buffer = new byte[1024];
            ms = new MemoryStream();
        }
    }
    public delegate  void  ReadDataComplectedEventHandler(byte[] data);

    class HtmlFromWebReq
    {

        private Uri url;

        public event ReadDataComplectedEventHandler OnReadDataComplected;

        public HtmlFromWebReq(string absoluteUrl)
        {
            url = new Uri(absoluteUrl);
        }
        protected void readDataCallback(IAsyncResult ar)
        {

            WebReqState rs = ar.AsyncState as WebReqState;
            int read = rs.OrginalStream.EndRead(ar);
            if (read > 0)
            {
                rs.ms.Write(rs.Buffer, 0, read);
                rs.OrginalStream.BeginRead(rs.Buffer, 0, WebReqState.BufferSize, new AsyncCallback(readDataCallback), rs);
            }
            else

            {
                rs.OrginalStream.Close();
                rs.WebResponse.Close();
                if (OnReadDataComplected != null)
                {
                    OnReadDataComplected(rs.ms.ToArray());
                }
            }

        }

        protected void responseCallback(IAsyncResult ar)
        {
            HttpWebRequest req = ar.AsyncState as HttpWebRequest;
            if (req == null)
                return;
            HttpWebResponse response = req.EndGetResponse(ar) as HttpWebResponse;
            if (response.StatusCode!= HttpStatusCode.OK)
            {
                response.Close();
                return;
            }
            WebReqState st=new WebReqState();
            st.WebResponse = response;
            Stream repsonseStream = response.GetResponseStream();
            st.OrginalStream = repsonseStream;
            repsonseStream.BeginRead(st.Buffer, 0, WebReqState.BufferSize, new AsyncCallback(readDataCallback), st);


        }

        public void BeginCreateHtml()
        {
            HttpWebRequest req = HttpWebRequest.Create(url.AbsoluteUri) as HttpWebRequest;
            req.BeginGetResponse( new AsyncCallback(responseCallback), req);
            
        }
         
    }
}