I have no idea why, but when I use URLConnection to send a http post request to a url, I can get rhe return fine, but when I use it in an if statement, it stops working.
The program compiles and all that, but if I was to use it to send a http request to a webpage containing yes, and I used the code if(answer.toString == "yes") it would not execute the code inside the if part. I know that it is probably to do with line seperators and such, but could anyone point to me how to fix it.
Code used to get the variable answer:
String data="param1=test1¶m2=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();
}
To compare java strings, use the
equalsmethod, not==.Because == can only detect if two strings are the same instance, not if they contain the same value.
So your test should be :
Note that I write “yes” as recipient of the equals method because writing
answer.equals("yes")would cause a NullPointerException when answer is null.In this case there is no risk of having answer null but it’s a good habit.