C# 通过URL调用接口6666666666666666666666666666666666666 5C

图片说明
怎么调用这个接口
下面是我写的代码

    /// <summary>
    /// 添加图片
    /// </summary>
    /// <param name="fp"></param>
    /// <returns></returns>
    public static int AddPhoto(FacePhoto fp)
    {
        string MethodPath = ipPath + "/face/create";
        Encoding myEncoding = Encoding.GetEncoding("gb2312");  //选择编码字符集
        string data = "pass=admin12345&personId=" + fp.personId + "&faceId=\"\"&imgBase64=data:image/jpg;base64," + fp.imgBase64;
        byte[] bytesToPost = System.Text.Encoding.Default.GetBytes(data); //转换为bytes数据
        string responseResult = String.Empty;
        HttpWebRequest req = (HttpWebRequest)
        HttpWebRequest.Create(MethodPath);   //创建一个httprequest请求
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
        req.ContentLength = bytesToPost.Length;
        using (Stream reqStream = req.GetRequestStream())
        {
            reqStream.Write(bytesToPost, 0, bytesToPost.Length);     //调用
        }
        HttpWebResponse cnblogsRespone = (HttpWebResponse)req.GetResponse();
        if (cnblogsRespone != null && cnblogsRespone.StatusCode == HttpStatusCode.OK)
        {
            StreamReader sr;
            using (sr = new StreamReader(cnblogsRespone.GetResponseStream()))
            {
                responseResult = sr.ReadToEnd();  //获取返回值
            }
            sr.Close();
        }
        cnblogsRespone.Close();
        DataResult item = JsonConvert.DeserializeObject<DataResult>(responseResult);
        if (item.success)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }

    /// <summary>
    /// 图片转Base64
    /// </summary>
    /// <param name="Imagefilename"></param>
    /// <returns></returns>
    public static string ImgToBase64String(string Imagefilename)
    {
        try
        {
            Bitmap bmp = new Bitmap(Imagefilename);
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            ms.Close();
            return Convert.ToBase64String(arr);
        }
        catch (Exception ex)
        {
            return null;
        }
    }

            调用返回java.lang.IllegalArgumentException: bad base-64

1个回答

bad base-64,说明你的base64编码有错误,或者参数的格式不对。我没有你的服务器没法帮你调试,你用fiddler自己抓包看看

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于c#使用WebClient调用openapi接口
使用c#调用openapi接口。如下图 ![图片说明](https://img-ask.csdn.net/upload/201703/06/1488785737_987974.jpg) java代码为: ``` public static PageResponse<UIMUser> userfind() { List<CommonCondition> conditions = new ArrayList<CommonCondition>(); CommonCondition c = new CommonCondition(); c.setName("userName"); c.setDataType(DataType.String); c.setCriteriaType(CriteriaType.StartWith); c.setValue("User1"); conditions.add(c); PostMethod method = new PostMethod(endPoint + "/admin/macula-uim/user/find"); try { method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // 标识是OpenAPI请求 method.addRequestHeader(OpenApiUtils.AJAX_REQUEST_HEADER, OpenApiUtils.API_REQUEST_VALUE); // 添加POST BODY method.addParameter("page", "0"); method.addParameter("rows", "20"); method.addParameters(OpenApiUtils.getPostParams("conditions", conditions)); // 设置请求参数 method.setQueryString(OpenApiUtils.getOpenApiParams(appKey, appSecret, null, null, null, null, "zh_CN", method.getParameters())); int status = client.executeMethod(method); String content = method.getResponseBodyAsString(); if (status == HttpServletResponse.SC_OK || status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { // 反序列化结果 ObjectMapperImpl mapper = new ObjectMapperImpl(); return mapper.readValue(content, new TypeReference<PageResponse<UIMUser>>() { }); } else { throw new Exception("错误的请求"); } } catch (Exception e) { e.printStackTrace(); } finally { method.releaseConnection(); } return null; } public static NameValuePair[] getPostParams(String objectName, Object obj) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); if (obj != null) { if (obj instanceof Map) { // 处理Map Map<?, ?> map = (Map<?, ?>) obj; for (Map.Entry<?, ?> entry : map.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); if (null != value) { pairs.addAll(Arrays.asList(getPostParams(objectName + "['" + key + "']", value))); } } } else if (obj instanceof Collection) { // 处理Collection Collection<?> col = (Collection<?>) obj; Iterator<?> it = col.iterator(); int index = 0; while (it.hasNext()) { Object value = it.next(); if (null != value) { pairs.addAll(Arrays.asList(getPostParams(objectName + "[" + index++ + "]", value))); } } } else if (!BeanUtils.isSimpleProperty(obj.getClass()) && !(obj instanceof Enum) && !Date.class.isAssignableFrom(obj.getClass())) { // 处理Bean BeanWrapperImpl bean = new BeanWrapperImpl(obj); PropertyDescriptor[] ps = bean.getPropertyDescriptors(); for (PropertyDescriptor p : ps) { if (!p.getName().equals("class")) { Object value = bean.getPropertyValue(p.getName()); if (null != value) { pairs.addAll(Arrays.asList(getPostParams(objectName + "." + p.getName(), value))); } } } } else { String str = obj.toString(); // 处理简单属性 // 日期格式使用ISO8601 if (obj instanceof Date) { str = DateFormatUtils.formatISO8601((Date) obj); } pairs.add(new NameValuePair(objectName, str)); } } return pairs.toArray(new NameValuePair[pairs.size()]); } ``` 现在不清楚使用c#怎么传递第一个参数。 我自己写的代码: ``` using (WebClient client = new WebClient()) { //SyncOrgDAL dal = new SyncOrgDAL(); // List<CommonCondition> conditions = new List<CommonCondition>(); //CommonCondition c = new CommonCondition(); //c.setName("userType"); //c.setDataType(DataType.String); //c.setCriteriaType(CriteriaType.Equals); //c.setValue("User1"); //conditions.Add(c); NameValueCollection postParams = new NameValueCollection { { "conditions", "[\"conditions\":{\"UserName\":\"Exp\",\"userType\":\"Exp\"}]" }, { "page", page.ToString() }, { "rows", pagesize.ToString() } }; //NameValueCollection postParams = new NameValueCollection { { "fromId", "302264246" }, { "toId", "99999999999" } }; string passString = Parameters.GetOpenApiParams(account, passWord, null, null, null, null, "zh_CN", postParams); //passString += "&userType=EMP"; url += passString; client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); client.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); client.Headers.Add("X-Requested-With", "OpenAPIRequest"); client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"); try { byte[] rDownData = client.UploadValues(url, "POST", postParams); var downString = Encoding.UTF8.GetString(rDownData) ?? ""; return downString; } catch (Exception ex) { return ex.ToString(); } finally { client.Dispose(); GC.Collect(); } ``` NameValueCollection postParams = new NameValueCollection { { "conditions", "[\"conditions\":{\"UserName\":\"Exp\",\"userType\":\"Exp\"}]" }, { "page", page.ToString() }, { "rows", pagesize.ToString() } }; 第一个参数什么格式。
C#webservice接口的调用
最近自己做了个webservice接口,部署在了自己的服务器上。我现在需要给别人去调用这个接口,并且需要把这个接口部署在他的服务器上,那么在调用这个webservice接口时我是否需要重新编译我这个调接口的程序,并且编译前把引用的web服务url上的IP地址改成他的?感觉这样做好费事啊,第一次做webservice接口请问大家都是这样调用的吗?有没有简单的方法?谢谢了!
C# 调用微信红包接口类中第三个参数strEncoding是什么意思
C# 调用微信红包接口类中第三个参数strEncoding是什么意思,如何取得。请大神指点。 public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding) { try { Encoding encoding = Encoding.UTF8; string cert = @"C:\zhengshu\apiclient_cert.p12"; string password = "xxxxxx";//这里是填写的是 微信支付商户号 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); X509Certificate cer = new X509Certificate(cert, password); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.ClientCertificates.Add(cer); request.Method = "post"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/x-www-form-urlencoded"; byte[] buffer = encoding.GetBytes(strPostdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding))) { return reader.ReadToEnd(); } } catch (Exception e) { return ""; } }
C#怎么获取网络接口?url写什么?token怎么验证?有点急。。。
``` string url = "xxxxx?PlateNumber=%E2%3A%36C78673&DeliveryPointCode=CC_0001"; WebRequest wRequest = WebRequest.Create(url); wRequest.Method = "GET"; wRequest.ContentType = "text/html;charset=UTF-8"; WebResponse wResponse = wRequest.GetResponse(); Stream stream = wResponse.GetResponseStream(); StreamReader reader = new StreamReader(stream, System.Text.Encoding.Default); string str = reader.ReadToEnd(); //url返回的值 reader.Close(); wResponse.Close(); ``` 在第四行wRequest.GetResponse()报了未授权的错误。![图片说明](https://img-ask.csdn.net/upload/201812/08/1544245888_57136.png) wRequest不为空,是因为我url写错了吗,还是wRequest的构造少东西了,厂商给我提供的token应该在哪体现在哪里呢?在Header里吗?代码怎么写呢?刚毕业第一次用这个。。。有好心人提供一个demo吗。。我真的搞不定了。。哎
C#窗体:通过URL打开浏览器,传参数的问题。
Process p = new Process(); p.StartInfo.FileName = "IExplore.exe"; p.StartInfo.Arguments = url; 求大神帮忙解答一下: 这个url我想调用我的java接口,但是我想传一些中文的参数过去,请问该怎么写?
C# 调用微信现金红包接口类网页没有任何反馈是什么意思?有没有大神给指导一下。
``` //请求api 带证书的方法 /// </summary> /// <param name="URL"></param> /// <param name="strPostdata"></param> /// <param name="strEncoding"></param> /// <returns></returns> public bool CheckValidationResult( Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors ) { // Always accept return true; } public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding) { try { Encoding encoding = Encoding.UTF8; string cert = @"C:\zhengshu\apiclient_cert.p12"; string password = "xxxxxxxxxx";//这里是填写的是 微信支付商户号 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); X509Certificate cer = new X509Certificate(cert, password); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.ClientCertificates.Add(cer); request.Method = "post"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/x-www-form-urlencoded"; byte[] buffer = encoding.GetBytes(strPostdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding))) { return reader.ReadToEnd(); } } catch (Exception e) { return ""; } } //调用OpenReadWithHttps方法 其中sendxml已经构造好了没有问题 Class1 ojb = new Class1(); ojb.OpenReadWithHttps(url, sendxml, "UTF-8"); ``` 现在就是网页没有认为反馈,按道理腾讯是不是应该回馈一个xml?我这里哪里又问题,请大神帮忙给看看。调用证书这块有没有问题,我将证书C:\zhengshu\apiclient_cert.p12放到这里目录里并安装了。
C#调用api接口返回json中错误信息一直是服务器繁忙
``` /// <summary> /// Interface类 /// </summary> public string Postdata(string postString, string url) { byte[] postData = Encoding.UTF8.GetBytes(postString); WebClient webClient = new WebClient(); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); byte[] responseData = webClient.UploadData(url, "post", postData); string srcString = Encoding.UTF8.GetString(responseData); return srcString; } //HomeController public ActionResult login(string Name, string Pwd, int type) { Interface inter = new Interface(); string hr = string.Format("Username ={0}&Password ={1}&JgRegistrationId={2}", Name, pwd, ""); var data = inter.Postdata(hr, "http://120.25.203.82:88/api/Session/Login"); } ``` ![图片说明](https://img-ask.csdn.net/upload/201611/07/1478498726_92164.png) ``` json的错误信息一直都是服务器繁忙 //服务器api Response Class (Status 200) OK ModelModel Schema xk.bohou.aomulaite.app.api.model.ResponseModel[xk.bohou.aomulaite.app.api.model.response.LoginModel] { ErrCode (string, optional): 错误信息 , Source (xk.bohou.aomulaite.app.api.model.response.LoginModel, optional): 数据 , ResultCode (string, optional): 结果状态:0成功、1失败 } ```
C# 微信上传图文消息内的图片获取URL
本人最近在做微信的后台接口, 因为需要群发图文消息, 内容里边会带图片, 所以需要调用这个接口 ![图片说明](https://img-ask.csdn.net/upload/201609/13/1473756780_25167.png) 他的调用示例让我用curl命令提交表单, 但是我查了一下, curl是php的, 那我c#怎么去上传图片获取URL, 有没有懂的, 教一下小弟, 在次谢过。
请教:关于从C#调用外部C++ DLL出错,二维指针参数不匹配
我是新人,头一次发帖,如果这个问题太低级还请各位大神原谅! 我在写一段C#代码调用外部一个C++DLL,该DLL数据初始化部分接口是这样的: public unsafe void SetImage(ushort** slices, int xSize, int ySize, int zSize) 其中第2-4个参数分别是一个3维图像数据的长宽高,我们假定图像是512×512×400;而这个二维指针参数slices则是指向指针的指针。说白了就是联合表示上述图像数据在内存中的地址,具体说其中每一个一维指针对应一张512×512大小图片在内存中的首地址,这个是已知的。而这个Slices则是指向这个连续的一维指针的首地址。假设每张图片的首地址我都已经存在ushort Iadd[]这个数组中了,我该这么构造这个slices才能让SetImage( slices, 512, 512, 400)真确编译呢? 搜索了网上很多内容,包括下面的帖子,但还是搞不定。 http://zhidao.baidu.com/link?url=7lov0mg2g49f0Ij25vtgaXIjP1gqH7MYXQIM9ylc0pUIB3DNOLHhCqasUz51UJ_OKJ0Kpi-tb8s2DN8Ey0K2f_ 先谢谢各位前辈了!
C#生成的类库 dll 无法在其它机注册
目前遇到c++调用C#写的DLL 问题,把C#的DLL注册为COM组件,在本机测试完成了,但在客户的机器上无法通过,注册的方式是通过Regasm 去注册dll 和tlb文件 ,但是排查注册表的时候发现未完全注册进去,在其它机器上是否需要加codebase,请各位大神帮帮忙,感谢 C#源码 C#中有调用外部DLL 接口: [Guid("3965F09B-9EE3-42F7-9908-CCA1BEC8603C")] public interface ICalc { [DispId(1)] void Join(string a,string b, out string c); } 类: [Guid("ABFADDE2-185D-4118-BC54-57458343BD8A")] [ClassInterface(ClassInterfaceType.None)] public class Calc:ICalc { public void Join(string a, string b, out string c) { string url = "tcp://10.1.1.198:8085"; ClientUtils.url = url; string cc = string.Empty; //DataSet ds = new DataSet(); //string ssql = "select * from sajet.sys_emp where emp_no = '" + b + "'"; //ds = ClientUtils.ExecuteSQL(ssql); //if (ds.Tables[0].Rows.Count > 0) //{ // cc = ds.Tables[0].Rows[0]["EMP_NAME"].ToString(); //} //else //{ // cc = "NG"; //} //c = cc; //return; if (a == "1") { object[][] Params = new object[16][]; Params[0] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet1", a }; Params[1] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet2", b }; Params[2] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet3", "" }; Params[3] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet4", "" }; Params[4] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet5", "" }; Params[5] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet6", "" }; Params[6] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet7", "" }; Params[7] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet8", "" }; Params[8] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet9", "" }; Params[9] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet10", "" }; Params[10] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet11", "" }; Params[11] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet12", "" }; Params[12] = new object[] { ParameterDirection.Input, OracleType.VarChar, "tsajet12ton", "" }; Params[13] = new object[] { ParameterDirection.Input, OracleType.VarChar, "trev", "" }; Params[14] = new object[] { ParameterDirection.Output, OracleType.VarChar, "TRES", "" }; Params[15] = new object[] { ParameterDirection.Output, OracleType.VarChar, "tnextproc", "" }; DataSet ds2 = ClientUtils.ExecuteProc("SAJET.COMMAND_CODE_OTP", Params); cc = ds2.Tables[0].Rows[0]["TRES"].ToString(); } c = cc; return; } }
c# 用winform程序实现HTTP中post请求
现在在做一个需求,要求用HTTP post方式调用接口实现数据上传,需求内容如下:协议:http方式:POST POST字符串参数为code={0}&keys={1}&writedoc={2} {0},{1},{2}分别对应参数code,keys,writedoc的值。 代码如下: string PostData = string.Format("code={0}&keys={1}&writedoc={2}", "10001", "d587fc05fe8c47b7", xmldoc); Uri url = new Uri(surl); WebRequest myHttpWebRequest = WebRequest.Create(url); myHttpWebRequest.Method = "POST"; myHttpWebRequest.Timeout = 3000; UTF8Encoding encoding = new UTF8Encoding(); byte[] byte1 = encoding.GetBytes(PostData); //myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"; myHttpWebRequest.ContentLength = byte1.Length; //发送成功后接收返回的XML信息 using (Stream newStream = myHttpWebRequest.GetRequestStream()) { newStream.Write(byte1, 0, byte1.Length); HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse(); string lcHtml = string.Empty; Encoding enc = Encoding.GetEncoding("UTF-8"); using(Stream stream = response.GetResponseStream()) { StreamReader streamReader = new StreamReader(stream, enc); lcHtml = streamReader.ReadToEnd(); return lcHtml; } } 可是在响应完成之后,服务器那边接收不到我窜过去的参数,各位大神看看我哪里写的不对
【小白提问】.net core 2.2 发布到IIS后 webapi 404错误
环境 .net core 2.2,ef core, 前台页面lay-ui 本机测试都正常,发布到IIS后,MVC 绑定数据都正常访问正常,Layui table ajax调用的都报404错误。 ![图片说明](https://img-ask.csdn.net/upload/201912/03/1575366379_942361.png) ![图片说明](https://img-ask.csdn.net/upload/201912/03/1575366361_646674.png) 接口代码: ``` [HttpPost] public IActionResult List() { _logger.LogInformation("==================={path}", HttpContext.Request.Path); Logger.Info(HttpContext.Request.Path); var result = new Object(); var success = new object(); var msg = new object(); var data = new object(); var code = 0; try { data = _context.ItemsLending.ToList(); Logger.Info(JsonConvert.SerializeObject(data));//此处调用日志记录函数记录日志 } catch (Exception e) { _logger.LogError("==================={path},{err}", HttpContext.Request.Path,e.Message); Logger.Info(e.Message);//此处调用日志记录函数记录日志 } result = (new { code, msg, data }); return Json(result); } ``` 尝试加了Log,发现完全没有调用这个接口,只有打开页面的log js ``` table.render({ elem: '#LendingList' , url: '/Lending/List/' , cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增 , method: 'post' , cols: [[ { field: 'id', title: 'Id', sort: true, templet: '#detail' } , { field: 'staffId', title: 'Staff ID' } , { field: 'item', title: 'Item' } , { field: 'lendingDate', title: 'Lending date', sort: true } , { field: 'preReturnDate', title: 'Pre return date' } , { field: 'returnDate', title: 'Return date' } , { field: 'status', title: 'Status' } , { field: 'remarks', title: 'Remarks', width: '20%', minWidth: 100 } //minWidth:局部定义当前单元格的最小宽度,layui 2.2.1 新增 ]] }); ```
C# winform程序实现JAVA josn 请求接
第一次写winfrom 不知道怎么写,以下是给的接口说明 HTTP请求方式:GET http://ip:port/lanshuijsdService/3.0/hts/queryCyr?param_key=?&secret_key=? 1) 注意: 以JSON格式传入输入参数 1) 请求参数 参数名称 类型 必需 描述 param_key 字符串 是 输入参数值 secret_key 字符串 是 Md5摘要信息 Param_key中包含的输入json中的字段描述如下: 参数名称 类型 必需 描述 meraccount string 是 商户账户(321000000) method string 是 API的资源操作方法名(queryCyr) timestamp number 是 用户发起请求时的unix时间戳。 v number 是 API版本号,默认使用最高版本(1.0)。 ⦁ 请求示例: 将param_key内的json中元素按照参数名排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串后进行MD5,以形成secret_key值 param_key值=RSA(URLEncoder ({”name2”:”value2”, “name1”:”value1”,”name3”:”value3”},”UTF-8”)) secret_key值= URLEncoder (md5(name1=value1& name2=value2&name3=value3) ,”UTF-8”) ⦁ 签名算法 服务API使用的签名算法如下: ⦁ 获取请求的HTTP method; ⦁ 获取请求的URL,包括host和scheme,但不包括query_string的部分 ⦁ 将所有参数(包括GET或POST的参数,但不包含签名字段)格式化为“key=value”格式,如“k1=v1”、“k2=v2”、“k3=v3”; ⦁ 将格式化好的参数键值对以字典序升序排列后,拼接在一起,如“k1=v1&k2=v2&k3=v3”,并将HTTP method和URL按顺序拼接在这个字符串前面; ⦁ 在拼接好的字符串末尾追加上应用的secret_key,并进行urlencode形成base_string; ⦁ 上述字符串的MD5值即为签名的值: sign= urlencode(MD5(k1=v1&k2=v2&k3=v3)); ⦁ 安全加密 为了确保敏感数据的可靠传输。必须对传输数据使用RSA的公钥进行非对称加密,私钥由服务提供方妥善保管,公钥由客户端经过身份验证之后获得。安全加密算法如下: RSA(URLEncoder ({”name2”:”value2”, “name1”:”value1”,”name3”:”value3”},”UTF-8”)) 分配的RSA公钥如下: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsoGCMo/XE+fNlLQBLK4VBYe8pVZe71Eb5fZOxd213vvshmWA/9c+vSM/uUAcD/W/It+xnJE1TECCTbV6uCqgfmrztwe2OQS2kGhLPGIYfo9ha2NufghUNAHAB9M0m1lp7y2m8T27iPhy 下面我写的代码: string strURL = "http://192.168.200.207:8088/lsjsdService/3.0/hts/queryJsd?param_key="; string md5 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GyRRxv35xuamvvnzQDOerH3yrrCLnJ6bQIDAQAB"; string pk="{\"val\":\"200005719465\",\"scode\":\"321000006\",\"date\":\"20180625\",\"flag\":\"0\",\"meraccount\":\"321000000\",\"method\":\"queryJsd\",\"v\":\"3.0\",\"timestamp\":\"20180707\",}"; string param_key = ToUrlEncode(pk); string sk = "var=200005719465&scode=321000006&date=20180625&flag=0&meraccount=321000000&method=queryJsd&v=3.0&timestamp=20180707"; string secret_key = sign(sk, md5, "UTF-8"); strURL = "http://192.168.200.207:8088/lsjsdService/3.0/hts/queryJsd?param_key=" + param_key + "&secret_key=" + secret_key; string h = HttpApi(strURL, "{}", "get"); public static string ToUrlEncode(string strCode) { StringBuilder sb = new StringBuilder(); byte[] byStr = System.Text.Encoding.UTF8.GetBytes(strCode); //默认是System.Text.Encoding.Default.GetBytes(str) System.Text.RegularExpressions.Regex regKey = new System.Text.RegularExpressions.Regex("^[A-Za-z0-9]+$"); for (int i = 0; i < byStr.Length; i++) { string strBy = Convert.ToChar(byStr[i]).ToString(); if (regKey.IsMatch(strBy)) { //是字母或者数字则不进行转换 sb.Append(strBy); } else { sb.Append(@"%" + Convert.ToString(byStr[i], 16)); } } return (sb.ToString()); } public static string sign(string content, string privateKey, string input_charset) { Encoding code = Encoding.GetEncoding(input_charset); byte[] Data = code.GetBytes(content); RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey); SHA1 sh = new SHA1CryptoServiceProvider(); byte[] signData = rsa.SignData(Data, sh); return Convert.ToBase64String(signData); } /// <summary> /// 调用api返回json /// </summary> /// <param name="url">api地址</param> /// <param name="jsonstr">接收参数</param> /// <param name="type">类型</param> /// <returns></returns> public static string HttpApi(string url, string jsonstr, string type) { Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址 request.Accept = "text/html,application/xhtml+xml,*/*"; request.ContentType = "application/json"; request.Method = type.ToUpper().ToString();//get或者post byte[] buffer = encoding.GetBytes(jsonstr); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } 文档里说的:param_key,secret_key 这两个值我都不知道我转换对没?以上我拼接的字符串正确吗?sign方法老是报错 ![图片说明](https://img-ask.csdn.net/upload/201807/08/1531032895_957209.png) 请大神帮忙指教下。
C# .net用controll如何通知支付宝交易成功
我用的MVC框架,"notifyurl"卸载Controll中,用接口调用的方式提供给支付宝做POST请求,能收到支付宝返回的支付信息,但数据处理之后,使用“Response.Write("success")”无法使支付宝继续回调该url。 我该如何处理? 大概代码如下: ```if (HttpContext.Current.Response.Form["trade_status"] == "TRADE_SUCCESS") { //这里写支付成功处理逻辑 //逻辑处理完成,告诉支付宝处理成功 HttpContext.Current.Response.Write("success"); //然而这里.Response.Write过去之后,支付宝还是会一如既往的回调url,知道满25个小时8次调用之后停止。 } ``` 请问各位大神有没有遇到这种情况,该如何处理?
c#异步通信代码错误问题
public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } //vs的这段代码中 ,bool connect_flag的connect_flag报了一个警告错误,变量connect_flag已赋值,但是其值从未使用过。如何修改? public static MODEL.DataSourceVersionQuery BrowseDataSource_QueryVersionData() { MODEL.DataSourceVersionQuery result = new MODEL.DataSourceVersionQuery(); //获取数据包 string strPacket = BrowseDataSource_PrepareVersionPacket(); //向服务端提交查询版本信息 string str = DAL.socket.GetSocketData(strPacket); //DAL.socket.GetSocketData(strPacket) vs报了一个错误,非静态字段、方法或属性DAL.socket.GetSocketData(string)“要求对象引用。如何修改? 还有这个错误![图片说明](https://img-ask.csdn.net/upload/201509/16/1442412249_893824.png) 另外我想把DAL中的socket.cs的 public byte[] bytesReceived { get; set; }这段移动到Model中而不报错要如何修改? DAL中socket完整代码如下: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Data; using System.Windows.Forms; using System.Threading; namespace DAL { /// <summary> /// Socket接口 /// </summary> class socket { //Socket public Socket clientSocket; /// <summary> /// socket连接 /// </summary> /// <returns> /// true 成功 /// false 失败 /// </returns> public bool SocketConnect() { byte[] bytesReceived = new byte[256]; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 //从配置文件获取IP string SocketIP = DAL.Common.ReadConfigString("Recover", "IP"); //从配置文件获取端口 int SocketPort = Convert.ToInt32(DAL.Common.ReadConfigString("Recover", "Port")); //创建IP地址 IPAddress IP = IPAddress.Parse(SocketIP); try { //创建socket实例 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建网络端点 IPEndPoint ipEnd = new IPEndPoint(IP, SocketPort); //与目标终端连接 clientSocket.BeginConnect(ipEnd, new AsyncCallback(ConnectCallback), clientSocket);//调用回调函数 connectDone.WaitOne(); if (clientSocket.Connected) { return true; } else { return false; } } catch (Exception e) { string strError = ""; strError += "\r\n SocketIP = " + SocketIP.ToString(); strError += "\r\n SocketPort = " + SocketPort.ToString(); DAL.Common.WriteErrorLog(e, strError); return false; } } /// <summary> /// 异步连接的回调函数 /// </summary> /// <param name="ar"></param> public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } /// <summary> /// Socket发送数据 /// </summary> /// <param name="strSend"> /// 数据的内容 /// </param> public void SocketSend(string strSend) { Socket clientSocket; //发送创建套接字 int length = strSend.Length; Byte[] bytesSent = new byte[length]; clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { bytesSent = System.Text.Encoding.Default.GetBytes(strSend); //将字符串指定到指定Byte数组 clientSocket.BeginSend(bytesSent, 0, bytesSent.Length, 0, new AsyncCallback(SendCallback), clientSocket); //异步发送数据 ManualResetEvent sendDone = new ManualResetEvent(false);//发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } } public void SendCallback(IAsyncResult ar) //发送的回调函数 { ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 Socket client = (Socket)ar.AsyncState; int bytesSend = client.EndSend(ar); //完成发送 sendDone.Set(); } /// <summary> /// Socket接收数据 /// </summary> /// <returns> /// 收到的数据 /// </returns> public string SocketReceive() { string result = ""; try { MemoryStream stream = new MemoryStream(); Byte[] bytesReceived = new Byte[256]; clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), clientSocket); ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public void ReceiveCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; //获取句柄 int bytesread = client.EndReceive(ar); if (bytesread > 0) { clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), client); string content = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length); } else { ManualResetEvent readDone = new ManualResetEvent(false); //读信号 readDone.Set(); } } /// <summary> /// Socket通信 /// </summary> /// <param name="strSend"> /// 发送的信息 /// </param> /// <returns> /// 包体的内容 /// </returns> public string GetSocketData(string strSend) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceive(); //获取扩展信息的长度 strExtLength = strResult.Substring(16, 12); int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 strDatas = strResult.Substring(ExtLength + 32); //strDatas = decodedString; } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public string SocketReceiveFile(string FileName) { string result = ""; try { MemoryStream streamPacketLength = new MemoryStream(); Byte[] bytesPacketLength = new Byte[16]; clientSocket.Receive(bytesPacketLength, bytesPacketLength.Length, 0); streamPacketLength.Write(bytesPacketLength, 0, bytesPacketLength.Length); result = System.Text.Encoding.Default.GetString(streamPacketLength.ToArray()); int PacketLength = Convert.ToInt32(result); streamPacketLength.Close(); MemoryStream streamExtLength = new MemoryStream(); Byte[] bytesExtLength = new Byte[12]; clientSocket.Receive(bytesExtLength, bytesExtLength.Length, 0); streamExtLength.Write(bytesExtLength, 0, bytesExtLength.Length); result = System.Text.Encoding.Default.GetString(streamExtLength.ToArray()); int ExtLength = Convert.ToInt32(result); streamExtLength.Close(); MemoryStream streamProtocol = new MemoryStream(); Byte[] bytesProtocol = new Byte[4]; clientSocket.Receive(bytesProtocol, bytesProtocol.Length, 0); streamProtocol.Write(bytesProtocol, 0, bytesProtocol.Length); result = System.Text.Encoding.Default.GetString(streamProtocol.ToArray()); string Protocol = result; streamProtocol.Close(); MemoryStream streamExtInfo = new MemoryStream(); Byte[] bytesExtInfo = new Byte[ExtLength]; clientSocket.Receive(bytesExtInfo, bytesExtInfo.Length, 0); streamExtInfo.Write(bytesExtInfo, 0, bytesExtInfo.Length); result = System.Text.Encoding.Default.GetString(streamExtInfo.ToArray()); byte[] Buffer = Convert.FromBase64String(result); string strExtInfo = UTF8Encoding.UTF8.GetString(Buffer); streamExtInfo.Close(); MODEL.FileTrackQuery ExtInfo = new MODEL.FileTrackQuery(); ExtInfo = JsonConvert.DeserializeObject<MODEL.FileTrackQuery>(strExtInfo); if (ExtInfo.code == "00") { FileInfo fi = new FileInfo(FileName); DirectoryInfo di = fi.Directory; if (!di.Exists) { di.Create(); } FileStream streamPacketInfo = new FileStream(FileName, FileMode.Create); if (PacketLength > 0) { Byte[] bytesPacketInfo = new Byte[PacketLength]; int bytes = 0; do { bytes = clientSocket.Receive(bytesPacketInfo, bytesPacketInfo.Length, 0); streamPacketInfo.Write(bytesPacketInfo, 0, bytes); } while (bytes > 0); } streamPacketInfo.Close(); } clientSocket.Close(); string strLogFile = System.AppDomain.CurrentDomain.BaseDirectory + "debug.txt"; StreamWriter sw = new StreamWriter(strLogFile, true); sw.WriteLine("PacketLength : " + PacketLength.ToString()); sw.WriteLine("ExtLength : " + ExtLength.ToString()); sw.WriteLine("strExtInfo : " + strExtInfo); sw.WriteLine("ExtInfo.code : " + ExtInfo.code); sw.WriteLine("\n------------------------------------------------------------------------\n"); sw.Flush(); sw.Close(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public string GetSocketFile(string strSend, string FileName) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceiveFile(FileName); //获取扩展信息的长度 //strExtLength = strResult.Substring(16, 12); //int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 //strDatas = strResult.Substring(ExtLength + 32); } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public byte[] bytesReceived { get; set; } } } MODEL完整代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MODEL { public enum ClientEditionEnum { Enterprise,//企业版 Personal,//个人版 Internal,//内部版 None,//error } /// <summary> /// 授权文件内容 /// </summary> public class AuthorizeFileInfo { public string startTime { get; set; } public string expiryTime { get; set; } public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public AuthorizeFileInfo() { startTime = ""; expiryTime = ""; licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; } } /// <summary> /// 通用返回值 /// </summary> /// public class CommonResult { public string code { get; set; } public string message { get; set; } public CommonResult() { code = ""; message = ""; } } public class EnterpriseConfirmAuthorizeDatas { public string sessionID { get; set; } public EnterpriseConfirmAuthorizeDatas() { sessionID = ""; } } /// <summary> /// 企业版授权校验接口 /// </summary> public class EnterpriseConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public EnterpriseConfirmAuthorizeDatas datas { get; set; } public EnterpriseConfirmAuthorizeResult() { code = ""; message = ""; datas = new EnterpriseConfirmAuthorizeDatas(); } } public class PersonalConfirmAuthorizeDatas { public string sessionID { get; set; } public string licenseInfo { get; set; } public PersonalConfirmAuthorizeDatas() { sessionID = ""; licenseInfo = ""; } } /// <summary> /// 个人版授权校验接口 /// </summary> public class PersonalConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public PersonalConfirmAuthorizeDatas datas { get; set; } public PersonalConfirmAuthorizeResult() { code = ""; message = ""; datas = new PersonalConfirmAuthorizeDatas(); } } /// <summary> /// 鉴权信息,每次调用安全接口时使用 /// </summary> public class LicInfo { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string deviceID { get; set; } public string sessionID { get; set; } public LicInfo() { licenseID = ""; licensePassword = ""; terminalID = ""; deviceID = ""; sessionID = ""; } } /// <summary> /// java引擎的参数 /// </summary> public class JavaEngineArg { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public string deviceID { get; set; } public JavaEngineArg() { licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; deviceID = ""; } } /// <summary> /// 用户登录接口(一),非安全接口 /// </summary> /// public class UserInfoUnSafe { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public UserInfoUnSafe() { userID = ""; userName = ""; departmentName = ""; } } public class UserLoginUnSafe { public string code { get; set; } public string message { get; set; } public UserInfoUnSafe datas { get; set; } public UserLoginUnSafe() { code = ""; message = ""; datas = new UserInfoUnSafe(); } } /// <summary> /// 个人版用户登录接口,非安全接口 /// </summary> /// public class UserInfoForPersonal { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string licenseInfo { get; set; } public UserInfoForPersonal() { userID = ""; userName = ""; departmentName = ""; licenseInfo = ""; } } public class UserLoginForPersonal { public string code { get; set; } public string message { get; set; } public UserInfoForPersonal datas { get; set; } public UserLoginForPersonal() { code = ""; message = ""; datas = new UserInfoForPersonal(); } } /// <summary> /// 用户登录接口(二),安全接口 /// </summary> /// public class UserInfoSafe { public string userSessionID { get; set; } public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string activeTime { get; set; } public UserInfoSafe() { userSessionID = ""; userID = ""; userName = ""; departmentName = ""; activeTime = ""; } } public class UserLoginSafe { public string code { get; set; } public string message { get; set; } public UserInfoSafe datas { get; set; } public UserLoginSafe() { code = ""; message = ""; datas = new UserInfoSafe(); } } /// <summary> /// 更新检查接口 /// </summary> /// public class SingleVersion { public string softID { get; set; } public int version { get; set; } public SingleVersion() { softID = ""; version = new int(); } } public class Versions { public List<SingleVersion> versions { get; set; } public Versions() { versions = new List<SingleVersion>(); } } public class VersionUpdate { public string softID { get; set; } public int version { get; set; } public string url { get; set; } public VersionUpdate() { softID = ""; version = new int(); url = ""; } } public class VersionCheck { public string code { get; set; } public string message { get; set; } public List<VersionUpdate> datas { get; set; } public VersionCheck() { code = ""; message = ""; datas = new List<VersionUpdate>(); } } /// <summary> /// 数据源信息查询接口 /// </summary> /// public class OptInfoQuery { public string createUserID { get; set; } public string createUserName { get; set; } public string createUserTime { get; set; } public OptInfoQuery() { createUserID = ""; createUserName = ""; createUserTime = ""; } } public class Period { public int cycle { get; set; } public int cycleUnit { get; set; } public string timer { get; set; } public Period() { cycle = 1; cycleUnit = 1; timer = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); } } public class StrategyConfig { public int backType { get; set; } public int taskType { get; set; } public Period config { get; set; } public StrategyConfig() { backType = 0; taskType = 1; config = new Period(); } } public class FilterFileSuffix { public string suffix { get; set; } public FilterFileSuffix() { suffix = ""; } } public class Scan { public int scanType { get; set; } public string root { get; set; } public bool scanHideFile { get; set; } public string verifyCompleteName { get; set; } public int verifyCompleteMaxCount { get; set; } public int verifyCompleteTimer { get; set; } public string fileAttrGainer { get; set; } public bool recordCanNotReadFileInfo { get; set; } public bool recordEmptyDirectory { get; set; } public bool recordEmptyFile { get; set; } public List<FilterFileSuffix> filterFileSuffix { get; set; } public Scan() { scanType = 2; root = ""; scanHideFile = false; verifyCompleteName = ""; verifyCompleteMaxCount = 5; verifyCompleteTimer = 10000; fileAttrGainer = "null"; recordCanNotReadFileInfo = false; recordEmptyDirectory = false; recordEmptyFile = false; filterFileSuffix = new List<FilterFileSuffix>(); } } public class DataSourceConfigQuery { public int status { get; set; } public int dataSourceType { get; set; } public string dataSourceID { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigQuery() { status = 0; dataSourceType = 0; dataSourceID = ""; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } public class DataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<DatasQuery> datas { get; set; } public DataSourceInfoQuery() { code = ""; message = ""; datas = new List<DatasQuery>(); } } public class WebSite { public string ExpirationTime { get; set; } public string WebSiteSpace { get; set; } public bool DataBaseEnable { get; set; } public string DataBaseUserName { get; set; } public string DataBasePassword { get; set; } public string DataBaseMark { get; set; } public string WebSiteAdmin { get; set; } public string WebSitePassword { get; set; } public WebSite() { ExpirationTime = ""; WebSiteSpace = ""; DataBaseEnable = false; DataBaseUserName = ""; DataBasePassword = ""; DataBaseMark = ""; WebSiteAdmin = ""; WebSitePassword = ""; } } public class WebSiteDatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public WebSite webSiteConfig { get; set; } public WebSiteDatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); webSiteConfig = new WebSite(); } } public class WebSiteDataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceInfoQuery() { code = ""; message = ""; datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 新增数据源接口 /// </summary> /// public class OptInfoNew { public bool forceFlag { get; set; } public OptInfoNew() { forceFlag = true; } } public class DataSourceConfigNew { public int dataSourceType { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigNew() { dataSourceType = 0; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DataSourceNew { public OptInfoNew optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigNew dataSourceConfig { get; set; } public DataSourceNew() { optInfo = new OptInfoNew(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigNew(); } } /// <summary> /// 修改数据源接口 /// </summary> /// public class DataSourceModify { public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DataSourceModify() { strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } /// <summary> /// 停用/启用数据源接口 /// </summary> /// public class DataSourceStatus { public string dataSourceID { get; set; } public int optType { get; set; } public DataSourceStatus() { dataSourceID = ""; optType = new int(); } } /// <summary> /// 数据源数据,仅用于存放数据 /// </summary> /// public class DataSourceData { public List<DatasQuery> datas { get; set; } public DataSourceData() { datas = new List<DatasQuery>(); } } /// <summary> /// WebSite数据源数据,仅用于存放数据 /// </summary> /// public class WebSiteDataSourceData { public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceData() { datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 文件恢复,版本查询 /// </summary> /// public class DataSourceVersionArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 前置机编号 public string terminalId { get; set; } // 操作用户编号 public string optUserID { get; set; } public DataSourceVersionArg() { secretKey = ""; token = ""; terminalId = ""; optUserID = ""; } } public class FileVersions { public int file_count { get; set; } public long space_size { get; set; } public string task_id { get; set; } public string task_time { get; set; } public int total_count { get; set; } public string version { get; set; } public FileVersions() { file_count = new int(); space_size = new long(); task_id = ""; task_time = ""; total_count = new int(); version = ""; } } public class DataSourceVersion { public Scan datasourceConfig { get; set; } public string datasourceId { get; set; } public string datasourceName { get; set; } public int datasourceStatus { get; set; } public int datasourceType { get; set; } public List<FileVersions> versions { get; set; } public DataSourceVersion() { datasourceConfig = new Scan(); datasourceId = ""; datasourceName = ""; datasourceStatus = new int(); datasourceType = new int(); versions = new List<FileVersions>(); } } /// <summary> /// 查询数据源接口 /// </summary> public class DataSourceVersionQuery { public string code { get; set; } public string message { get; set; } public List<DataSourceVersion> datas { get; set; } public DataSourceVersionQuery() { code = ""; message = ""; datas = new List<DataSourceVersion>(); } } /// <summary> /// 数据源版本信息 /// </summary> public class DataSourceVersionDatas { public List<DataSourceVersion> datas { get; set; } public DataSourceVersionDatas() { datas = new List<DataSourceVersion>(); } } /// <summary> /// 文件恢复,文件信息查询 /// </summary> /// public class QueryFileInfoArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 数据源编号 public string datasourceId { get; set; } // 操作用户编号 public string optUserID { get; set; } // 目录文件编号--如果为根目录使用 DS_ROOT public string fileID { get; set; } // 查询的版本编号 如果是综合分析 这个字段设置为 ALL public string taskID { get; set; } public QueryFileInfoArg() { secretKey = ""; token = ""; datasourceId = ""; optUserID = ""; fileID = ""; taskID = ""; } } public class FileInfoCondition { public string datasourceId { get; set; } public string parentId { get; set; } public string taskID { get; set; } public FileInfoCondition() { datasourceId = ""; parentId = ""; taskID = ""; } } public class FileInfo { // 文件唯一编号 public string file_id { get; set; } // 源相对目录 public string file_src_path { get; set; } // 文件名 public string file_name { get; set; } // 文件后缀 public string file_suffix { get; set; } // 是否为文件 public bool is_file { get; set; } // 上级文件编号 public string parent_id { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件大小 public int size { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 是否可读 public bool can_read { get; set; } public FileInfo() { file_id = ""; file_src_path = ""; file_name = ""; file_suffix = ""; is_file = new bool(); parent_id = ""; is_del = new bool(); is_hide = new bool(); size = new int(); create_time = ""; create_user = ""; lm_time = ""; lm_user = ""; can_read = new bool(); } } public class FileInfoAndCondition { public FileInfoCondition condition { get; set; } public List<FileInfo> fileInfos { get; set; } public FileInfoAndCondition() { condition = new FileInfoCondition(); fileInfos = new List<FileInfo>(); } } /// <summary> /// 查询文件信息接口 /// </summary> public class FileInfoQuery { public string code { get; set; } public string message { get; set; } public FileInfoAndCondition datas { get; set; } public FileInfoQuery() { code = ""; message = ""; datas = new FileInfoAndCondition(); } } /// <summary> /// 文件信息 /// </summary> public class FileInfoData { public List<FileInfo> datas { get; set; } public FileInfoData() { datas = new List<FileInfo>(); } } public class QueryFileTrackArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 文件编号 public string fileID { get; set; } // 操作用户编号 public string optUserID { get; set; } // 查询的版本编号 public string taskID { get; set; } public QueryFileTrackArg() { secretKey = ""; token = ""; fileID = ""; optUserID = ""; taskID = ""; } } public class FileTrack { // 文件操作 public string act_cmd { get; set; } // 是否可读 public bool can_read { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 文件大小 public int size { get; set; } public string taskID { get; set; } public FileTrack() { act_cmd = ""; can_read = new bool(); create_time = ""; create_user = ""; is_del = new bool(); is_hide = new bool(); lm_time = ""; lm_user = ""; size = new int(); taskID = ""; } } public class FileTrackCondition { public string fileID { get; set; } public string taskID { get; set; } public FileTrackCondition() { fileID = ""; taskID = ""; } } /// <summary> /// 查询文件轨迹接口 /// </summary> public class FileTrackQuery { public string code { get; set; } public string message { get; set; } public FileTrackCondition condition { get; set; } public List<FileTrack> datas { get; set; } public FileTrackQuery() { code = ""; message = ""; condition = new FileTrackCondition(); datas = new List<FileTrack>(); } } /// <summary> /// 文件轨迹 /// </summary> public class FileTrackData { public List<FileTrack> datas { get; set; } public FileTrackData() { datas = new List<FileTrack>(); } } /// <summary> /// 字典item /// </summary> public class DictionaryData { public string version { get; set; } public string task_time { get; set; } public DictionaryData() { version = ""; task_time = ""; } } public class FileRecoverArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 操作用户编号 public string optUserID { get; set; } public string fileID { get; set; } public string taskID { get; set; } public string password { get; set; } public FileRecoverArg() { secretKey = ""; token = ""; optUserID = ""; fileID = ""; taskID = ""; password = ""; } } }
调用护照识别仪接口同一段代码跑出两个不同的返回值
老哥们,近期在调试护照识别仪时,测试工程可以正常调用接口,而正式工程里面调用则不正常,先上api代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReadPassPortReaderLibrary { using System.Runtime.InteropServices; using System.IO; using System.Collections; /// <summary> /// 文通阅读器 /// </summary> public class PassPortWT { [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int InitIDCard(char[] cArrUserID, int nType, char[] cArrDirectory); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int GetRecogResult(int nIndex, char[] cArrBuffer, ref int nBufferLen); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int RecogIDCard(); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int GetFieldName(int nIndex, char[] cArrBuffer, ref int nBufferLen); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int AcquireImage(int nCardType); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int SaveImage(char[] cArrFileName); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int SaveHeadImage(char[] cArrFileName); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int GetCurrentDevice(char[] cArrDeviceName, int nLength); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern void GetVersionInfo(char[] cArrVersion, int nLength); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern bool CheckDeviceOnline(); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern bool SetAcquireImageType(int nLightType, int nImageType); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern bool SetUserDefinedImageSize(int nWidth, int nHeight); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern bool SetAcquireImageResolution(int nResolutionX, int nResolutionY); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int SetIDCardID(int nMainID, int[] nSubID, int nSubIdCount); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int AddIDCardID(int nMainID, int[] nSubID, int nSubIdCount); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int RecogIDCardEX(int nMainID, int nSubID); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int GetButtonDownType(); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int GetGrabSignalType(); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int SetSpecialAttribute(int nType, int nSet); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern void FreeIDCard(); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int GetDeviceSN(char[] cArrSn, int nLength); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int GetBusinessCardResult(int nID, int nIndex, char[] cArrBuffer, ref int nBufferLen); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int RecogBusinessCard(int nType); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int GetBusinessCardFieldName(int nID, char[] cArrBuffer, ref int nBufferLen); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int GetBusinessCardResultCount(int nID); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int LoadImageToMemory(string path, int nType); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int ClassifyIDCard(ref int nCardType); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int RecogChipCard(int nDGGroup, bool bRecogVIZ, int nSaveImageType); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int RecogGeneralMRZCard(bool bRecogVIZ, int nSaveImageType); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int RecogCommonCard(int nSaveImageType); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int SaveImageEx(char[] lpFileName, int nType); [DllImport(@"wintone\IDCard", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)] public static extern int GetDataGroupContent(int nDGIndex, bool bRawData, byte[] lpBuffer, ref int len); private string error = ""; private bool m_bIsIDCardLoaded = false;//标记认识引擎是否已经加载 //保存图片目录 private string saveimagepath = AppDomain.CurrentDomain.BaseDirectory + "\\passwordimage\\"; //初始化的路径,即相关动态库文件 存放的路径, 如果相关文 件和可执行件放在了同一目录,可以传 件放在了同一目录,可以传 件放在了同一目录,可以传 NULL ;否 则需要传递绝对路径 private string workpath = AppDomain.CurrentDomain.BaseDirectory + "\\wintone\\"; //private string workpath = "D:\\昆明金硅\\旅馆\\客户端\\19\\HotelClient\\HotelClient\\bin\\Debug\\wintone\\"; //保存图片的文件名称 private string imagefilename = "passport.jpg"; private string imageheadfilename = "passportHead.jpg"; private string imageIRfilename = "passportIR.jpg"; private Hashtable map = new Hashtable(); public string getType()//护照类型 { string type = getData("MRZ1"); return type.Substring(0, 1); } public string getCountryCode()//国家码 { return getData("签发国代码"); } public string getPassportNo()//护照号码 { return getData("护照号码MRZ"); } public string getEnfirstname()//英文姓 { return getData("英文姓"); } public string getEnsecondname()//英文名 { return getData("英文名"); } public string getEnname()//英文姓名 { return getData("英文姓名"); } public string getChnname()//本国姓名 { return getData("本国姓名"); } public string getSex()//性别 { return getData("性别"); } public string getSexCode()//性别 { string s = getData("性别"); if (s == "男") return "M"; else return "F"; } public string getNationalty()//国籍代码 { return getData("持证人国籍代码"); } public string getBirth()//出生 { return getData("出生日期"); } public string getPlaceBirth()//出生地点 { return getData("出生地点"); } public string getDateIssue()//签发日期 { return getData("签发日期"); } public string getPlaceIssue() { return getData("签发地点"); } public string getDateExpiry()//有效期至 { return getData("有效期至"); } public string getAuthority()//签发机关 { return getData("签发机关OCR"); } private byte[] readFileToByte(string filename) { FileStream f = null; try { f = new FileStream(filename, FileMode.Open, FileAccess.Read); byte[] b = new byte[f.Length]; f.Read(b, 0, b.Length); return b; } finally { f.Close(); } } private void delImageFile() { string[] filelists = Directory.GetFiles(saveimagepath); foreach (string filename in filelists) { FileInfo finfo = new FileInfo(filename); if (File.Exists(saveimagepath + "\\" + finfo.Name)) File.Delete(saveimagepath + "\\" + finfo.Name); } //if (File.Exists(saveimagepath + imagefilename)) // File.Delete(saveimagepath + imagefilename); //if (File.Exists(saveimagepath + imageheadfilename)) // File.Delete(saveimagepath + imageheadfilename); //if (File.Exists(saveimagepath + imageIRfilename)) // File.Delete(saveimagepath + imageIRfilename); } private string getData(string key) { if (map.Count <= 0) return ""; foreach (DictionaryEntry mapde in map) { if (mapde.Key.ToString() == key) { return (string)mapde.Value; } } return ""; } /// <summary> /// 获得UserID /// 约束条件:在运行目录下要有文件UserId.txt,文件内容是:UserId=66066608373290781564 /// 如果没有具备约束条件的将返回一个缺省值66066608373290781564 /// </summary> /// <returns>UserID</returns> private string getUserID() { string useridfilename = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "UserId.txt"; if (File.Exists(useridfilename)) { byte[] b = readFileToByte(useridfilename); if (b == null) { return "66066608373290781564"; } string s = Encoding.Default.GetString(b); if (string.IsNullOrEmpty(s)) { return "66066608373290781564"; } string[] ss = s.Split('='); if (ss.Length == 2) { return ss[1]; } } return "66066608373290781564"; } public string getError() { return error; } public void setSaveImagePath(string pathname) { if (!string.IsNullOrEmpty(pathname)) { if (!Directory.Exists(pathname)) { Directory.CreateDirectory(pathname); } this.saveimagepath = pathname; } } /// <summary> /// 设置相关动态库文件 存放的路径 /// </summary> /// <param name="pathname"></param> //public void setEnginePath(string pathname) //{ // if (!string.IsNullOrEmpty(pathname)) // { // if(Directory.Exists(pathname)) // { // this.workpath = pathname; // } // } //} /// <summary> /// 获得证件图片的URL字符串,如果文件不存在返回空字符串 /// </summary> /// <returns></returns> public string getImageUrl() { if (File.Exists(saveimagepath + imagefilename)) return saveimagepath + imagefilename; else return ""; } /// <summary> /// 获得证件头像图片的URL字符串,如果文件不存在返回空字符串 /// </summary> /// <returns></returns> public string getImageHeadUrl() { if (File.Exists(saveimagepath + imageheadfilename)) return saveimagepath + imageheadfilename; else return ""; } /// <summary> /// 获得证件白光图片的URL字符串,如果文件不存在返回空字符串 /// </summary> /// <returns></returns> public string getImageIRUrl() { if (File.Exists(saveimagepath + imageIRfilename)) return saveimagepath + imageIRfilename; else return ""; } public Hashtable getValues() { return map; } public bool LoadEngine() { map.Clear(); m_bIsIDCardLoaded = false; string userid = getUserID(); int nRet; char[] charuserid = userid.ToCharArray(); char[] work = workpath.ToCharArray(); nRet = InitIDCard(charuserid, 1, work); if (nRet != 0) { error = "初始化认识引擎错误"; return false; } //测试工程nRet返回值为0,调用正确,正式工程是nRet返回值为3调用不成功 SetSpecialAttribute(1, 1); m_bIsIDCardLoaded = true; return true; } public void CloseEngine() { if (m_bIsIDCardLoaded) { FreeIDCard(); m_bIsIDCardLoaded = false; } } public string getVersion() { error = ""; if (!m_bIsIDCardLoaded) { error = "没有加载认识引擎"; throw new Exception(error); } char[] cArrVersion = new char[128]; GetVersionInfo(cArrVersion, 128); return new String(cArrVersion); } public string getDeviceName() { error = ""; if (!m_bIsIDCardLoaded) { error = "没有加载认识引擎"; throw new Exception(error); } char[] cArrDeviceName = new char[128]; GetCurrentDevice(cArrDeviceName, 128); return new String(cArrDeviceName); } public bool hasOnLine() { error = ""; if (!m_bIsIDCardLoaded) { error = "没有加载认识引擎"; throw new Exception(error); } return CheckDeviceOnline(); } public string getDeviceSN() { error = ""; if (!m_bIsIDCardLoaded) { error = "没有加载认识引擎"; throw new Exception(error); } char[] cArrSN = new char[16]; GetDeviceSN(cArrSN, 16); return new String(cArrSN); } private bool _recognize() { int nRet = 0; int[] nSubID = new int[1]; nSubID[0] = 0; SetIDCardID(2, nSubID, 1);//设置当前要识别的证件类型,并将 设置当前要识别的证件类型,并将之前已经设置的证件类型清除。 AddIDCardID(3, nSubID, 1);//增加识别的证件类型 AddIDCardID(4, nSubID, 1); AddIDCardID(5, nSubID, 1); AddIDCardID(6, nSubID, 1); AddIDCardID(7, nSubID, 1); AddIDCardID(9, nSubID, 1); AddIDCardID(10, nSubID, 1); AddIDCardID(11, nSubID, 1); AddIDCardID(12, nSubID, 1); AddIDCardID(13, nSubID, 1); AddIDCardID(14, nSubID, 1); AddIDCardID(15, nSubID, 1); AddIDCardID(16, nSubID, 1); AddIDCardID(22, nSubID, 1); AddIDCardID(25, nSubID, 1); AddIDCardID(26, nSubID, 1); int nCardType = 0; nRet = ClassifyIDCard(ref nCardType);//对即将识别的证件自动分类 if (nRet <= 0) { error = "分类失败"; return false; } //get param int nDG = 15; int nSaveImage = 11; bool bVIZ = true; if (nCardType == 1)//带芯片的证件 { nRet = RecogChipCard(nDG, bVIZ, nSaveImage);//识别带电子芯片的证件 } if (nCardType == 2)//带MRZ护照证件 { nRet = RecogGeneralMRZCard(bVIZ, nSaveImage);//识别带有 MRZ的护照类证件 } if (nCardType == 3)//不带MRZ护照证件 { nRet = RecogCommonCard(nSaveImage);//识别普通证件 } if (nRet < 0) { error = "识别失败"; return false; } int MAX_CH_NUM = 128; char[] cArrFieldValue = new char[MAX_CH_NUM]; char[] cArrFieldName = new char[MAX_CH_NUM]; string field = ""; string value = ""; int indexv = 0; for (int i = 1; ; i++) { field = ""; value = ""; nRet = GetRecogResult(i, cArrFieldValue, ref MAX_CH_NUM);//取得识别结果 if (nRet == 3) { break; } GetFieldName(i, cArrFieldName, ref MAX_CH_NUM);//取得识别单元的字段名 field = new String(cArrFieldName); indexv = field.IndexOf("\0"); if (indexv > 0) { field = field.Substring(0, indexv); } value = new String(cArrFieldValue); indexv = value.IndexOf("\0"); if (indexv > 0) { value = value.Substring(0, indexv); } map.Add(field, value); } //SaveImage String strRunPath = saveimagepath; String strImgPath = strRunPath + imagefilename; char[] carrImgPath = strImgPath.ToCharArray(); nRet = SaveImageEx(carrImgPath, nSaveImage);//将采集到内存中的所有图像保到硬盘 if (nRet != 0) { error = "保存照片失败"; return false; } return true; } /// <summary> /// 手动识别 /// </summary> /// <returns></returns> public bool startRecognize() { map.Clear(); delImageFile(); error = ""; if (!m_bIsIDCardLoaded) { error = "没有加载认识引擎"; throw new Exception(error); } return _recognize(); } } } 接下来上调用的代码 private PassPortWT wt; private void btnReadPassPort_Click(object sender, EventArgs e) { if (AppConfigManager.Hotelinfo.qtxx1 != "Y") { zMsgBox.Error("未授权使用护照识别仪,请联系维护人员!"); return; } zWait.Show(); try { wt = new PassPortWT(); bool f = wt.LoadEngine(); //正式工程返回false,调用不正确 if (!f) { zMsgBox.Error(wt.getError()); } else { ReadPassPort(); } zWait.Hide(); } catch (Exception ex) { zWait.Hide(); zMsgBox.Error(ex.Message); } } 正式工程跟测试工程调用的代码是一模一样的,请问有没有有经验的老哥给指点一下这个咋回事
c#.net jsapi微信支付提示缺少参数total_fee
页面 <script type="text/javascript"> wx.config({ debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: '<%=AppId %>', // 必填,公众号的唯一标识 timestamp: "<%=Timer %>", // 必填,生成签名的时间戳 nonceStr: "<%=RdCode %>", // 必填,生成签名的随机串 signature: "<%=GetSignature() %>", // 必填,签名,见附录1 jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); wx.ready(function () { wx.chooseWXPay({ appId: '<%=AppId %>', timestamp: '<%=Timer %>', nonceStr: '<%=RdCode %>', package: 'prepay_id=<%=prepay_id%>', signType: 'MD5', paySign: '<%=paySign %>', success: function (res) { }, cancel: function () { }, error: function (e) { } }); }); </script> 后台 public void GetprepayIdAndpaySign() { //公众账号ID string appid = AppId; //商品描述 string OrderCode = DateTime.Now.ToString("yyyyMMddHHmmss"); string body = "订单号:" + OrderCode; //商户号 string mch_id = "1262625001"; //随机字符串 string nonce_str = RdCode; //通知地址-接收微信支付成功通知 string notify_url = "http://a.k-bean.com/notify_url.aspx"; //用户标识 -用户在商户appid下的唯一标识 string openid = OpenId; //商户订单号 string out_trade_no = OrderCode; //下单IP string spbill_create_ip = GetIP(this.Context); //总金额 分为单位 int total_fee = 1; //交易类型 -JSAPI、NATIVE、APP 如果是生成二维码请填写NATIVE string trade_type = "JSAPI"; //微信签名 string tmpStr = "appid=" + appid + "&body=" + body + "&mch_id=" + mch_id + "&nonce_str=" + nonce_str + "&notify_url=" + notify_url + "&openid=" + openid + "&out_trade_no=" + out_trade_no + "&spbill_create_ip=" + spbill_create_ip + "&total_fee=" + total_fee + "&trade_type=" + trade_type + "&key=" + key + ""; string Getprepay_idSign = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "MD5").ToUpper(); string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; string xml = "<xml>"; xml += "<appid>" + appid + "</appid>"; xml += "<body>" + body + "</body>"; xml += "<mch_id>" + mch_id + "</mch_id>"; xml += "<nonce_str>" + nonce_str + "</nonce_str>"; xml += "<notify_url>" + notify_url + "</notify_url>"; xml += "<openid>" + openid + "</openid>"; xml += "<out_trade_no>" + out_trade_no + "</out_trade_no>"; xml += "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"; xml += "<total_fee>" + total_fee + "</total_fee>"; xml += "<trade_type>" + trade_type + "</trade_type>"; xml += "<sign>" + Getprepay_idSign + "</sign>"; xml += "</xml>"; string v = PostWebRequests(url, xml); //获取的prepay_id prepay_id = v; //获取paySign,请对照前后台的大小写 string v_tmpStr = "appId=" + appid + "&nonceStr=" + RdCode + "&package=prepay_id=" + v + "&signType=MD5&timeStamp=" + Timer + "&key=" + key + ""; paySign = FormsAuthentication.HashPasswordForStoringInConfigFile(v_tmpStr, "MD5").ToUpper(); }
asp.net开发支付宝接口使用官方SDK后第一次跳转支付速度非常慢,是我调用问题还是结构有问题?
``` // 组装业务参数model AlipayTradePagePayModel model = new AlipayTradePagePayModel(); model.Body = body; model.Subject = subject; model.TotalAmount = total_amout; model.OutTradeNo = out_trade_no; model.PassbackParams = System.Web.HttpUtility.UrlEncode(strXml.ToString(), System.Text.Encoding.GetEncoding("GB2312")); ; model.ProductCode = "FAST_INSTANT_TRADE_PAY"; AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 设置同步回调地址 request.SetReturnUrl("http://" + HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.Url.Port + "/AliPay/Return_url.aspx"); //request.SetReturnUrl($"http://"+ HttpContext.Current.Request.Url.Host +":" + HttpContext.Current.Request.Url.Port + "/AliPay/test.aspx"); // 设置异步通知接收地址 request.SetNotifyUrl(System.Configuration.ConfigurationManager.AppSettings["ReturnWebUrl"]); // 将业务model载入到request request.SetBizModel(model); AlipayTradePagePayResponse response = null; try { response = client.pageExecute(request); Response.Write(response.Body); Response.Flush(); Response.Close(); } catch (Exception exp) { throw exp; } ```
萤石开发平台http接口出现301 Moved Permanently
我可以获取到accessToken, 官方API文档https://open.ys7.com/doc/zh/book/index/device_option.html 比如在调用c6h的预置位1,为什么会出现下附带的301页面被重定位的地址,https://open.ys7.com/api/lapp/device/preset/move,不是对这个地址请求吗, 或者查询其他的功能,都会出现301网页被重定向,求原因分析。 我用的语言是python34 我现在每次调各个功能,都是返回如下的重定向错误 <title>301 Moved Permanently</title> 301 Moved Permanently The requested resource has been assigned a new permanent URI. python3.4 代码如下: def devices_list():#调用预置位 global accessToken #accessToken='at.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' test_data1 = { 'accessToken':accessToken,'deviceSerial':'XXXXXX','channelNo':1,'index':1} test_data_urlencode1=urllib.parse.urlencode(test_data1).encode('utf-8') print(test_data_urlencode1) requrl1='https://open.ys7.com/api/lapp/device/preset/move'#请求调用预置位的地址 headerdata1={ 'Content-type': 'application/x-www-form-urlencoded', 'Host':'open.ys7.com' } conn1=http.client.HTTPConnection("open.ys7.com") conn1.request("POST",url=requrl1,body=test_data_urlencode1,headers=headerdata1) response1=conn1.getresponse() print(response1.status) print(response1.reason) jump=response1.headers['Location'] print(jump) res2=response1.read().decode('utf-8') print(res2) devices_list()
相见恨晚的超实用网站
搞学习 知乎:www.zhihu.com 简答题:http://www.jiandati.com/ 网易公开课:https://open.163.com/ted/ 网易云课堂:https://study.163.com/ 中国大学MOOC:www.icourse163.org 网易云课堂:study.163.com 哔哩哔哩弹幕网:www.bilibili.com 我要自学网:www.51zxw
花了20分钟,给女朋友们写了一个web版群聊程序
参考博客 [1]https://www.byteslounge.com/tutorials/java-ee-html5-websocket-example
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
字节跳动视频编解码面经
引言 本文主要是记录一下面试字节跳动的经历。 三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。 七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时
开源一个功能完整的SpringBoot项目框架
福利来了,给大家带来一个福利。 最近想了解一下有关Spring Boot的开源项目,看了很多开源的框架,大多是一些demo或者是一个未成形的项目,基本功能都不完整,尤其是用户权限和菜单方面几乎没有完整的。 想到我之前做的框架,里面通用模块有:用户模块,权限模块,菜单模块,功能模块也齐全了,每一个功能都是完整的。 打算把这个框架分享出来,供大家使用和学习。 为什么用框架? 框架可以学习整体
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
Python——画一棵漂亮的樱花树(不同种樱花+玫瑰+圣诞树喔)
最近翻到一篇知乎,上面有不少用Python(大多是turtle库)绘制的树图,感觉很漂亮,我整理了一下,挑了一些我觉得不错的代码分享给大家(这些我都测试过,确实可以生成喔~) one 樱花树 动态生成樱花 效果图(这个是动态的): 实现代码 import turtle as T import random import time # 画樱花的躯干(60,t) def Tree(branch
深深的码丨Java HashMap 透析
HashMap 相关概念 HashTab、HashMap、TreeMap 均以键值对像是存储或操作数据元素。HashTab继承自Dictionary,HashMap、TreeMap继承自AbstractMap,三者均实现Map接口 **HashTab:**同步哈希表,不支持null键或值,因为同步导致性能影响,很少被使用 **HashMap:**应用较多的非同步哈希表,支持null键或值,是键值对...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
Python 基础(一):入门必备知识
目录1 标识符2 关键字3 引号4 编码5 输入输出6 缩进7 多行8 注释9 数据类型10 运算符10.1 常用运算符10.2 运算符优先级 1 标识符 标识符是编程时使用的名字,用于给变量、函数、语句块等命名,Python 中标识符由字母、数字、下划线组成,不能以数字开头,区分大小写。 以下划线开头的标识符有特殊含义,单下划线开头的标识符,如:_xxx ,表示不能直接访问的类属性,需通过类提供
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
JDK12 Collectors.teeing 你真的需要了解一下
前言 在 Java 12 里面有个非常好用但在官方 JEP 没有公布的功能,因为它只是 Collector 中的一个小改动,它的作用是 merge 两个 collector 的结果,这句话显得很抽象,老规矩,我们先来看个图(这真是一个不和谐的图????): 管道改造经常会用这个小东西,通常我们叫它「三通」,它的主要作用就是将 downstream1 和 downstre...
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员...
相关热词 c# plc s1200 c#里氏转换原则 c# 主界面 c# do loop c#存为组套 模板 c# 停掉协程 c# rgb 读取图片 c# 图片颜色调整 最快 c#多张图片上传 c#密封类与密封方法
立即提问