3

I sent a GET message with socket. And I received response message as string. But I want to receive as hexadecimal. But I didn't accomplish. This is my code block as 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);
                    }
Fatih ELMA
  • 65
  • 2
  • 8
  • it means you want to read the input from socket in a `byte[]` format..??? – ELITE May 16 '15 at 11:57
  • may this is helpful http://stackoverflow.com/questions/4117791/read-binary-data-from-a-socket – Viraj Nalawade May 16 '15 at 12:03
  • you are right NiRRaNjAN RauT. it must be byte[] . – Fatih ELMA May 16 '15 at 12:05
  • then try with the following answer..it may help you.. – ELITE May 16 '15 at 12:06
  • If you want to receive something in hexadecimal notation then it should first of all be sent in hexadecimal notation. Please tell first what is going on. – greenapps May 16 '15 at 12:42
  • `I sent a GET message with socket.` Really? Very special. Usually one sends a GET request with a http component. Please explain why you use a socket directly. – greenapps May 16 '15 at 12:44
  • You are right but this is my graduation project. And we wanted to sent GET message as manually. Actually I didnt want to use socket. But I dont know TCP/IP. Socket already make this layer. – Fatih ELMA May 16 '15 at 12:49

1 Answers1

3

when you use BufferedReader you'll get the input into String format..so better way to use InputStream...

here is sample code to achieve this.

        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 getting the 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

reference from java-code-to-convert-byte-to-hexadecimal

Community
  • 1
  • 1
ELITE
  • 5,815
  • 3
  • 19
  • 29
  • Actually I must receive as hexadecimal. I just learned it. https://code.google.com/p/rest-client/issues/detail?id=171. Do you have an idea about this? – Fatih ELMA May 16 '15 at 12:32
  • you can convert `byte[]` to hex string using `String.format();` method – ELITE May 16 '15 at 16:48