由于项目需要,做的c#客户端数据库连接串首先肯定不能写死的程序里(数据库很容易被攻击,我们的项目半年改了几次密码。。。)
放置在配置文件内,都可以看得到,最开始想法将配置文件加密,老师说加密过的文件还是不安全。。。。。
最后的方法就是c#这边调用java的api返回连接串(它们那边做了不知道什么权限的)使用的HttpRequest,一下是postman里的结果(两个入参用于实现每次请求的校验)
在网上找了一段代码做个demo单个参数是成功执行。。。
下面是我的修改后代码
try { HttpWResp = (HttpWebResponse)myReq.GetResponse(); } catch (WebException ex) { HttpWResp = (HttpWebResponse)ex.Response; }
这段代码可以让你看到你的错误,返回的结果是什么,例如
返回下面的这部分东西,加上上面那句话,错误可以看到。。。
一般的错误就是
HttpWResp = (HttpWebResponse)myReq.GetResponse(); 出现异常,出现异常的原因最可能是参数出现问题(如果url有效且create成功了)插入一下request的几种方式
application/x-www-form-urlencoded 一般参数就是拼接的形式a=A&b=B....
application/json 参数就是以json的形式被发送 var
data = {
‘title‘
:
‘test‘
,
‘sub‘
: [1,2,3]};
我自己出现的问题就是两个入参的时候用的type是
application/x-www-form-urlencoded 所以我以为入参的形式就是a=A&b=B...还甚至认为是没加双引号的问题
string strRequestData = "{A:5800a00d00000000, B: 1901234567891193}";最后将入参改成了这种形式就好了
(其实这里很疑惑,用的入参类型和入参方式不匹配,明明应该是拼接的参数啊。。。。。。。。。。。。)
private static string Post(string strUrl, string paramA, string paramB) { StringBuilder responseData = new StringBuilder(); Encoding code = Encoding.GetEncoding("UTF-8"); //待请求参数数组字符串 //string strRequestData = HttpUtility.UrlEncode("A", code) + "=" + HttpUtility.UrlEncode(paramA, code) + "&" + HttpUtility.UrlEncode("B", code) + "=" + HttpUtility.UrlEncode(paramB, code); //string strRequestData = "companyName=" + Uri.EscapeDataString(companyName); //string strRequestData = "{A=" + paramA + "&" + "B=" + paramB + "}"; string A = "5800a00d00000000"; string B = "1901234567891193"; //string strRequestData = "A=" + A + "&" + "B=" + B; string strRequestData = "{A:5800a00d00000000, B: 1901234567891193}"; //string strRequestData = { "A":"5800a00d00000000","A":"5800a00d00000000"}; //string strRequestData = HttpUtility.UrlEncode("companyName", code) + "=" + HttpUtility.UrlEncode("969325639000980000000001", code); //把数组转换成流中所需字节数组类型 byte[] bytesRequestData = Encoding.UTF8.GetBytes(strRequestData); //byte[] bytesRequestData = encoding.GetBytes(strRequestData); //构造请求地址 string strResult = ""; //请求远程HTTP try { //设置HttpWebRequest基本信息 HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(strUrl); myReq.Timeout = 5000; myReq.Method = "post"; myReq.ContentType = "application /x-www-form-urlencoded"; //填充POST数据 myReq.ContentLength = bytesRequestData.Length; Stream requestStream = myReq.GetRequestStream(); requestStream.Write(bytesRequestData, 0, bytesRequestData.Length); requestStream.Close(); //发送POST数据请求服务器 HttpWebResponse HttpWResp; try { HttpWResp = (HttpWebResponse)myReq.GetResponse(); } catch (WebException ex) { HttpWResp = (HttpWebResponse)ex.Response; } Stream myStream = HttpWResp.GetResponseStream(); //获取服务器返回信息 StreamReader reader = new StreamReader(myStream, code); String line; while ((line = reader.ReadLine()) != null) { responseData.Append(line); } myReq.KeepAlive = false; //释放 myStream.Close(); strResult = responseData.ToString(); } catch (Exception exp) { strResult = "报错:" + exp.Message; } return responseData.ToString(); }
时间: 2024-10-12 16:39:49