gpt4 book ai didi

使用从 URLConnection 读取的值的 Java If 语句不起作用

转载 作者:行者123 更新时间:2023-12-01 15:20:43 24 4
gpt4 key购买 nike

我不知道为什么,但是当我使用 URLConnection 向 url 发送 http post 请求时,我可以很好地返回,但是当我在 if 语句中使用它时,它停止工作。 该程序编译了所有这些,但如果我要使用它向包含 yes 的网页发送 http 请求,并且我使用代码 if(answer.toString == "yes") 它不会执行 if 部分内的代码。我知道这可能与行分隔符等有关,但是任何人都可以指出我如何修复它。

用于获取变量answer的代码:

String data="param1=test1&param2=test2";
try{
URL lUrl=new URL("http://localhost/test.php");
URLConnection conn=lUrl.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer=new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
StringBuffer answer=new StringBuffer();
BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line=reader.readLine())!=null){
answer.append(line);
}
writer.close();
reader.close();
if(answer.toString()=="yes"){
System.out.print("1");
}else{
System.out.print(answer.toString());
}
}catch(MalformedURLException ex){
ex.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
}

最佳答案

要比较 Java 字符串,请使用 equals 方法,而不是 ==

因为 == 只能检测两个字符串是否是同一个实例,而不能检测它们是否包含相同的值。

所以你的测试应该是:

if ("yes".equals(answer)) {

请注意,我将“yes”写为 equals 方法的接收者,因为当答案为 null 时,写 answer.equals("yes") 会导致 NullPointerException。在这种情况下,不存在答案为 null 的风险,但这是一个好习惯。

关于使用从 URLConnection 读取的值的 Java If 语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10964171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com