我试图将字节数组转换为十六进制字符串。但我最终没有内存错误异常。我对此一无所知。
private String byteArrayToHexString(byte[] array) {
StringBuffer hexString = new StringBuffer();
for (byte b : array) {
int intVal = b & 0xff;
if (intVal < 0x10)
hexString.append("0");
hexString.append(Integer.toHexString(intVal));
}
return hexString.toString();
感谢您的帮助
答案 0 :(得分:0)
发送前不转换 - 发送时转换
答案 1 :(得分:0)
这是一个例子。您基本上想先连接到Web服务器,然后直接在输出流中将图像转换为hexstring,这样字节就直接转到服务器,您不必先将整个图像转换为巨大的字符串然后把它推到服务器上。
byte[] array; // This is your byte array containing the image
URL url = new URL("http://yourwebserver.com/image-upload-or-whatever");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
// Now you have an output stream that is connected to the webserver that you can
// write the content into
for (byte b : array) {
// Get the ASCII character for the first and second digits of the byte
int firstDigit = ((b >> 4) & 0xF) + '0';
int nextDigit = (b & 0xF) + '0';
out.write(firstDigit);
out.write(nextDigit);
}
out.flush(); // ensure all data in the stream is sent
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in); // Read any response
} finally {
urlConnection.disconnect();
}
我没有尝试过这段代码,但希望你明白这一点。