最近政府那边做了一个不动产过户给水电气热推送过户信息得接口。
用了C# webapi
被动接收来自不动产和大数据那边的推送数据,给了数据格式。做完之后与那边技术对接一头包暂且不提。
期间发现接收的请求都获取不到参数,在排除自身问题的时候,尝试了多种方法。
最终问题解决如下:
[HttpPost]
[Route("~/xxxx")]
public object xxxx()
{
Stream s = HttpContext.Current.Request.GetBufferedInputStream();
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
string a = Encoding.UTF8.GetString(b);
}
期间尝试了
public object pushDjData(dynamic obj)
public object pushDjData([FromBody]zhuang obj)
都不好用
对方直接给了请求的java代码
public static String post(String strURL,String params) {
try{
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/x");
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out.append(params);
out.flush();
out.close();
int length = connection.getContentLength();
InputStream is = connection.getInputStream();
if(length != -1){
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ( (readLen = is.read(temp)) > 0){
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
return new String(data, "UTF-8");
}
}catch (IOException e){
System.out.println(e.getMessage());
if("Connection timed out: connect".equals(e.getMessage())){
return "no connect";
}
e.printStackTrace();
}
return "error";
}
值得一提的是
Stream s = HttpContext.Current.Request.GetBufferedInputStream();
一开始写法是
Stream s = HttpContext.Current.Request.InputStream;
报了错误
在 HttpRequest.GetBufferedInputStream 的调用方填充内部存储之前访问了 BinaryRead、表单、文件或 InputStream;
通过流的方式是否可以取到body里面的请求参数,我跟我同事测试结果不一致,有待后期发现。