... var uri = new Uri(url); //能够获取cookie的HttpClient CookieContainer cookieContainer = new CookieContainer(); var handler = new HttpClientHandler(); handler.CookieContainer = cookieContainer; HttpClient httpClient = new HttpClient(handler); //请求头设置 httpClient.DefaultRequestHeaders.Host = host; //这个必须要 httpClient.DefaultRequestHeaders.Referrer = new Uri( refer); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("image/*")); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("*/*"));//Accept: image/webp,image/apng,image/*,*/*;q=0.8 HttpResponseMessage response = httpClient.GetAsync(url).Result; //返回格式 response.Headers.Add("Content_Type", "image/png"); if (response.IsSuccessStatusCode) { // byte[] urlContents = await response.Content.ReadAsByteArrayAsync(); //获取返回的流 stream = await response.Content.ReadAsStreamAsync(); //获取cookie List<Cookie> cookies = cookieContainer.GetCookies(uri).Cast<Cookie>().ToList(); foreach (var item in cookies) { sb_cookie.Append(item.Name); sb_cookie.Append("="); sb_cookie.Append(item.Value); sb_cookie.Append(";"); } string result = response.Content.ReadAsStringAsync().Result; return result; } return null;
img_jym.Image = Image.FromStream(stream);//这样就构建了验证码图片了
发送验证码验证
//构建请求表单formDictionary<string, string> dic2 = new Dictionary<string, string>(); dic2.Add("captcha", txt_jym.Text); HttpContent content2 = new FormUrlEncodedContent(dic2.ToList()); //设置手动添加cookie的HttpClient var handler = new HttpClientHandler() { UseCookies = false }; var httpClient = new HttpClient(handler); httpClient.DefaultRequestHeaders.Host = host; httpClient.DefaultRequestHeaders.Referrer = new Uri(refer); //添加cookie httpClient.DefaultRequestHeaders.Add("Cookie", sb_cookie.ToString()); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("*/*"));//Accept: image/webp,image/apng,image/*,*/*; HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; response.Headers.Add("Content_Type", "application/x-www-form-urlencoded; charset=UTF-8");//Content-Type: application/x-www-form-urlencoded; charset=UTF-8最后发送成绩查询的请求和发送验证码请求一样的。 代码写得很乱,httpclient都没dispose,多开几次,内存就会升上来得。 源码下载://files.cnblogs.com/files/HelloQLQ/RuanKaoScoreQuery.zip 博客写得很敷衍,只追求博客随笔得数量,不追求博客内容质量!