我的Java代码总是给出错误的值,但我的API是真的吗?

时间:2015-06-05 09:58:58

标签: java

我的代码有问题。

这是一张图片

结果始终为false

但在我的API中

两个结果都是true

这是 Java 代码的一部分。有什么帮助吗?

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("in.txt"));
        PrintWriter out = new PrintWriter(new FileWriter("result.txt"), true);     
        String User;

        while ((User = br.readLine()) != null){
            URL url = new URL("http://mysecretweb.com/r/migrate.php?name="+User);
            URLConnection connection = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            boolean result = Boolean.valueOf(reader.readLine());
            String str = Boolean.toString(result);
            System.out.println(User+" is "+str);
            out.write(User+" is "+str);
            out.write("\r\n");               
            }

        }

    }

2 个答案:

答案 0 :(得分:0)

使用java转储调用的原始结果。 Boolean.valueOf(value)仅当您正在阅读的第一行可解析为&#34时才为true; true"

如果该行包含其他字符,例如网页标题或是html页面,或者内容包含空格......则无法解析。

转储结果和文本有多少行的代码示例(真正简单和虚假,但功能齐全)。如果它有空格。

public class StackTest {
    public static void main(String[] args) throws IOException {
        String userToTest="something";
        URL url = new URL("http://mysecretweb.com/r/migrate.php?name=" + userToTest);
        URLConnection connection = url.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        do{
            line = reader.readLine();
            System.out.print("|");
            System.out.print(line);
            System.out.println("|");
        }while(line!=null);
        reader.close();
    }
}

答案 1 :(得分:-1)

您可以使用InputStreamReader reader=new InputStreamReader(connection.getInputStream());代替BufferedReader reader = new BufferedReader(new InputStreamReader ( connection.getInputStream())),然后您就可以获得最佳输出。

public class Main {
        public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader("in.txt"));
        PrintWriter out = new PrintWriter(new FileWriter("result.txt"), true);

        String user;

        while ((user = br.readLine()) != null){

            URL url = new URL("http://gagqga.gq/r/migrate.php?name="+user);
            URLConnection connection = url.openConnection();
            // BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            InputStreamReader reader=new InputStreamReader(connection.getInputStream());

            boolean result = Boolean.valueOf(reader.ready());

            String str = Boolean.toString(result);
            System.out.println(user+" is "+str);
            out.write(user+" is "+str);
            out.write("\r\n");     

           }

       }  

   }