How can I get the socket input as hex?
I sent a GET message with a socket. And I got the reply message as a string. But I want to get as hex. But I didn't get it. This is my code block as a string. Can you help me?
dos = new DataOutputStream(socket.getOutputStream());
dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
dos.write(requestMessage.getBytes());
String data = "";
StringBuilder sb = new StringBuilder();
while ((data = dis.readLine()) != null) {
sb.append(data);
}
+3
source to share
1 answer
when you use BufferedReader
you will get input in format String
. Best to use InputStream
...
here is some sample code for that.
InputStream in = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] read = new byte[1024];
int len;
while((len = in.read(read)) > -1) {
baos.write(read, 0, len);
}
// this is the final byte array which contains the data
// read from Socket
byte[] bytes = baos.toByteArray();
after receiving byte[]
you can convert it to hex string using the following function
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());// here sb is hexadecimal string
+3
source to share