Java 将图像从J2ME客户端上载到Servlet
我想从J2ME客户机向Servlet发送一个图像 我能够获得图像的字节数组,并使用HTTPPOST发送它Java 将图像从J2ME客户端上载到Servlet,java,image,servlets,java-me,Java,Image,Servlets,Java Me,我想从J2ME客户机向Servlet发送一个图像 我能够获得图像的字节数组,并使用HTTPPOST发送它 conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true); conn.setRequestMethod(HttpConnection.POST); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); os
conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os.write(bytes, 0, bytes.length); // bytes = byte array of image
以下是Servlet代码:
String line;
BufferedReader r1 = new BufferedReader(new InputStreamReader(in));
while ((line = r1.readLine()) != null) {
System.out.println("line=" + line);
buf.append(line);
}
String s = buf.toString();
byte[] img_byte = s.getBytes();
但我发现的问题是,当我从J2ME客户端发送字节时,一些字节丢失了。它们的值是0A
和0D
hex。准确地说,回车和换行
因此,POST方法或readLine()
都不能接受0A
和0D
值
任何人都知道怎么做,或者如何使用其他方法吗?这是因为您正在使用
缓冲读取器
逐行读取二进制流。readLine()。这些单独的行不再包含CRLF
不要对二进制流使用BufferedReader
,这没有意义。只需将获得的InputStream
写入任何风格的OutputStream
,例如FileOutputStream
也就是说,您使用的内容类型
在技术上是错误的。您没有在请求正文中发送WWW表单URL编码的值。您正在发送一个二进制流。它应该是应用程序/octet流
或者可能是图像
。这不是问题的原因,但它完全是错误的。这是因为您正在使用BufferedReader
逐行读取二进制流。readLine()。这些单独的行不再包含CRLF
不要对二进制流使用BufferedReader
,这没有意义。只需将获得的InputStream
写入任何风格的OutputStream
,例如FileOutputStream
也就是说,您使用的内容类型
在技术上是错误的。您没有在请求正文中发送WWW表单URL编码的值。您正在发送一个二进制流。它应该是应用程序/octet流
或者可能是图像
。这不是这个问题的原因,但它完全是错误的
InputStream input = null;
OutputStream output = null;
try {
input = request.getInputStream();
output = new FileOutputStream("/path/to/file.ext");
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer()) > 0;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) output.close();
if (input != null) input.close();
}