Java URL Connection StreamReader 问题读取结果
Java URL Connection StreamReader issue reading results
在将信息发布到网页后阅读回复时,我遇到了一个奇怪的问题。控制台打印 "success" 但代码中的检查失败,并且在检查发生时最后返回 false 而不是 true。
点击页面的php脚本如下:
<?php
echo "success";
?>
最终它会接受发布的信息,但现在我只想将它用于我的应用程序,看看它是否可以连接到它的目标。
public static boolean checkConnect(String cURL) {
try{
URLConnection connect = new URL(cURL).openConnection();
connect.setDoOutput(true);
connect.setRequestProperty("Accept-Charset", charset);
connect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write("this is a test");
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String line;
String results = "";
while ((line = rd.readLine()) != null) {
results += line;
}
//prints "success" to console.
System.out.println(results.trim());
//fails
if (results.trim() =="success")
return true;
wr.close();
rd.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
在 Java 中,String 是一个对象。
要将 String 与某些内容进行比较,您必须使用 equals 方法。
If(results.trim().equals("success")){}
在将信息发布到网页后阅读回复时,我遇到了一个奇怪的问题。控制台打印 "success" 但代码中的检查失败,并且在检查发生时最后返回 false 而不是 true。
点击页面的php脚本如下:
<?php
echo "success";
?>
最终它会接受发布的信息,但现在我只想将它用于我的应用程序,看看它是否可以连接到它的目标。
public static boolean checkConnect(String cURL) {
try{
URLConnection connect = new URL(cURL).openConnection();
connect.setDoOutput(true);
connect.setRequestProperty("Accept-Charset", charset);
connect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write("this is a test");
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String line;
String results = "";
while ((line = rd.readLine()) != null) {
results += line;
}
//prints "success" to console.
System.out.println(results.trim());
//fails
if (results.trim() =="success")
return true;
wr.close();
rd.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
在 Java 中,String 是一个对象。 要将 String 与某些内容进行比较,您必须使用 equals 方法。
If(results.trim().equals("success")){}