1

Im trying to connect to a php script on a server and retrieve the text the script echoes.Do accomplish I used the following code.

CODE:=

import java.net.*;
import java.io.*;
class con{
public static void main(String[] args){
    try{
        int c;
        URL tj = new URL("http://www.thejoint.cf/test.php");
        URLConnection tjcon = tj.openConnection();
        InputStream input = tjcon.getInputStream();
        while(((c = input.read()) != -1)){
            System.out.print((char) c);
        }
        input.close();
    }catch(Exception e){
        System.out.println("Caught this Exception:"+e);
    }
    }
}

I do get the desired output that is the text "You will be Very successful".But when I remove the (char) type casting it yields a 76 digit long. 8911111732119105108108329810132118101114121321151179999101115115102117108108 number which I'm not able to make sense of.I read that the getInputStream is a byte stream, then should there be number of digits times 8 number long output? Any insight would be very helpful, Thank you

Mrak Vladar
  • 598
  • 4
  • 18

1 Answers1

3

It does not print one number 76 digits long. You have a loop there, it prints a lot of numbers, each up to three digits long (one byte).

In ASCII, 89 = "Y", 111 = "o" ....

What the cast to char that you removed did was that it interpreted that number as a Unicode code point and printed the corresponding characters instead (also one at a time).

This way of reading text byte by byte is very fragile. It basically only works with ASCII. You should be using a Reader to wrap the InputStream. Then you can read char and String directly (and it will take care of character sets such as Unicode).

Oh I thought it would give out the byte representation of the individual letter.

But that's exactly what it does. You can see it more clearly if you use println instead of print (then it will print each number on its own line).

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Thank You sir..!, and what I meant by byte is the binary representation of the individual letter. – Mrak Vladar Jun 03 '19 at 10:15
  • 1
    Ah, you mean bits? Those are of course all present in the `byte`, but not normally printed as eight bits, but as a decimal or (most frequent) in hex (such as `0x6E`). You could, if you want, though: https://stackoverflow.com/questions/5263187/print-an-integer-in-binary-format-in-java – Thilo Jun 03 '19 at 10:48