zoukankan      html  css  js  c++  java
  • todo WebClient学习

    [HttpGet]
    public ContentResult VerifyProduct(string jsoncallback,string code)
    {
    code = code.ToUpper();//全部转换成大写
    string result = string.Empty;
    if (!string.IsNullOrEmpty(code) && code.Length >= 11)//截取前11位
    {
    code = code.Substring(0, 11);
    }
    try
    {
    string postString = "code=" + code;//这里即为传递的参数,可以用工具抓包分析,也可以自己分析,主要是form里面每一个name都要加进来
    byte[] postData = Encoding.UTF8.GetBytes(postString);//编码,尤其是汉字,事先要看下抓取网页的编码方式
    string url = "http://h41105.www4.hp.com/ok/cn/zh/verify.asp";//地址

    #region 模拟Post请求
    WebClient webClient = new WebClient();
    webClient.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
    webClient.Headers.Add("Accept: text/html, application/xhtml+xml, */*");
    webClient.Headers.Add("Content-Type: application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
    webClient.Headers.Add("Host: h41105.www4.hp.com");
    #region 代理设置
    if ("1".Equals(IsWebProxy))
    {
    WebProxy wp = new WebProxy("http://" + WebProxyURL + ":" + WebProxyPort + "", true);
    NetworkCredential credential = new NetworkCredential(CredentialUserName, CredentialPassword, Domain);
    wp.Credentials = credential;
    webClient.Proxy = wp;
    }
    #endregion
    webClient.Headers.Add("Accept-Language: zh-CN");
    webClient.Headers.Add("Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7");
    #endregion

    #region 返回结果
    byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流
    string srcString = Encoding.UTF8.GetString(responseData);//解码
    string keyWords = String.Concat("产品 ", code, " 为正品");//返回内容的关键字
    string keyWords2 = String.Concat("产品 ", code, " 无效");
    string keyWords3 = "输入的序列号出错。请检查防伪标签并重试。";//核查情况

    #endregion

    #region 根据返回结果判断显示内容

    if (srcString.IndexOf(keyWords) > -1)//根据关键字 进行查找
    {
    result = String.Concat("产品 ", code, " 为正品");//正品
    }
    else if (srcString.IndexOf(keyWords2) > -1)
    {
    result = String.Concat("产品 ", code, " 无效");//无效
    }
    else if (srcString.IndexOf(keyWords3) > -1)
    {
    result = "输入的序列号出错。请检查防伪标签并重试。";
    }
    else { result = "请稍后再试"; }//验证失败,其它原因
    #endregion

    }
    catch(System.Net.WebException webx)
    {
    result = "请稍后再试";
    log.Error("VerifyProduct_WebException=" + webx.ToString() + ",wex.Status=" + webx.Status);
    }
    catch (Exception ex)
    {
    result = "请稍后再试";
    log.Error("VerifyProduct_Error", ex);
    }

    string output = JavaScriptConvert.SerializeObject(result);
    return Content(jsoncallback + "(" + output + ")");
    }

  • 相关阅读:
    Paint类的介绍
    缓存淘汰算法之LRU
    Android SurfaceView实战 打造抽奖转盘
    android中scrollTo和scrollBy的理解
    Android View.onMeasure方法的理解
    Android Context 上下文 你必须知道的一切
    Android Animation简述
    Markdown 语法说明
    理解Java虚拟机体系结构
    Java集合框架:HashMap
  • 原文地址:https://www.cnblogs.com/Amity/p/3157414.html
Copyright © 2011-2022 走看看