gpt4 book ai didi

java - 如何将字节数据从 C# 传递到 Java 中的 Servlet

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:37 26 4
gpt4 key购买 nike

我正在尝试将字节数据从 C# 传递到 java servlet。代码如下:

byte[] data = futronicApp.getFingerVerificationData(name,SampleModel);
String passingData = "cust_no=" + name + "&serial=" + serial + "&temp=" + data;
jsonparser = new JSONParser("http://10.11.201.31:8085/FingerEnrollVerify/EnrolledFingerVerify", "POST", passingData );

JSONParser类的定义如下:

public JSONParser(string url)
{
// Create a request using a URL that can receive a post.
request = WebRequest.Create(url);
}
public JSONParser(string url, string method) : this(url)
{
if (method.Equals("GET") || method.Equals("POST"))
{
// Set the Method property of the request to POST.
request.Method = method;
}
else
{
throw new Exception("Invalid Method Type");
}
}
public JSONParser(string url, string method, string data) : this(url, method)
{
// Create POST data and convert it to a byte array.
string postData = data;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}

然后在 java servlet 中我试图获取这个字节数据。代码如下:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


System.out.println("Finger Enroll Verify");

String customerNumber = request.getParameter("cust_no");
System.out.println("cust_no is "+customerNumber);


String serial = request.getParameter("serial");
int serial_no = Integer.parseInt(serial);
System.out.println("Serial_no is "+serial_no);

InputStream inputStream = request.getInputStream();
byte[] fingerbytes = IOUtils.toByteArray(inputStream);
System.out.println("fingerbytes length: "+fingerbytes.length);
}

但我得到的是 "fingerbytes length: 0"。为什么 ?如何将字节数据从 C# 传递到 Java servlet?请帮我 。

最佳答案

bytes 不能像这样对待 chars。实际上这不起作用的原因是因为您有一个包含不同类型数据的字符串。

通常您会将字节“流”到服务器而不是将它们“字符串化”,因为字节的字符串表示通常是数字。

幸运的是,虽然有一个内置函数允许这样做......

String passingData = "cust_no=" + name + "&serial=" + serial + "&temp=" + System.Text.Encoding.Default.GetString(data);

这将使您的整个帖子成为一个字符串,

然后在 Java 端你将不得不从字节数组中拆分字符串,并通过使用像......这样的东西反向拆分成相同的。

var dataString = postedString.split("&temp=")[1];
var data = dataString.getBytes();

关于java - 如何将字节数据从 C# 传递到 Java 中的 Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com