我正在尝试连接到服务器上的 php
脚本并检索脚本回显的文本。完成我使用了以下代码。
代码:=
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);
}
}
}
我确实得到了文本“You will be Very successful”所需的输出。但是当我删除 (char)
类型转换时,它会产生 76 位长。
8911111732119105108108329810132118101114121321151179999101115115102117108108
我无法理解的数字。我读到 getInputStream
是一个 byte stream
,那么应该有数字乘以 8 数字长输出吗?
任何见解都会非常有帮助,谢谢
最佳答案
它不会打印一个 76 位长的数字。那里有一个循环,它会打印很多数字,每个数字最多三位数字(一个字节)。
在 ASCII 中,89 =“Y”,111 =“o”....
您删除的转换为 char
的操作是将该数字解释为 Unicode 代码点并打印相应的字符(也是一次一个)。
这种逐字节读取文本的方式非常脆弱。它基本上只适用于 ASCII。您应该使用 Reader
来包装 InputStream
。然后你可以直接读取char
和String
(它会处理Unicode等字符集)。
Oh I thought it would give out the byte representation of the individual letter.
但这正是它的作用。
如果您使用 println
而不是 print
,您可以更清楚地看到它(然后它将在其自己的行上打印每个数字)。
关于java - 在 URLconnection 对象上以什么格式发送数据,getInputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56425127/