[英]How do I compare two Strings being used for URLs
我正在编写一个应用程序,该应用程序查看服务器上托管的文件,如果更改,它将加载并重新加载Webview。 这用于在设备之间复制许多网页。
我使用以下方法设置了初始网址:
private String originalURL;
private String newURL;
然后定义一个在onCreate上使用
originalURL = "https://www.buzzfeed.com/sallytamarkin/total-body-workouts#.moYPngWVWy";
然后,我在计时器上运行异步任务:
private static String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
// many of these calls can throw exceptions, so i've just
// wrapped them all in one try/catch statement.
try
{
// create a url object
URL url = new URL(theUrl);
// create a urlconnection object
URLConnection urlConnection = url.openConnection();
// wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
// read from the urlconnection via the bufferedreader
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
private class BackgroundTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// perform your network logic here
String output = getUrlContents("http://52.30.226.234/url.txt");
System.out.println("output is " + output);
newURL = output;
return "YourResult";
}
@Override
protected void onPostExecute(String result) {
// Update your screen with the results.
}
}
但是,当我尝试比较两个字符串时,它们始终会得出不同的结果。 我已经尝试过match(),equals()和equalsIgnoreCase()。 这是我正在使用的代码
if ((originalURL.equals(newURL))==true) {
System.out.println("SAME");
} else {
System.out.println("NOT SAME");
}
}
我还使用前面定义的两个字符串对此进行了测试,并且效果很好。
我只能认为这是由于特殊字符引起的,但是已经尝试了一些修复程序来删除特殊字符,但这也没有用。
请帮忙!
不要在if-clause
写“ true”;
如果要Case-Sensitive
执行以下操作:
if(string1.equals(string2)){
System.out.println("SAME");
}
else{
System.out.println("NOT SAME");
}
如果您希望Case-Insensitive
执行以下操作:
if(string1.equalsIgnoreCase(string2)){
System.out.println("SAME");
}
else{
System.out.println("NOT SAME");
}
如果它不符合您的要求,或者您想进行更严格的比较,请尝试使用整理器
可能是由于网址末尾出现乱码。 这部分经常更改。 打印以查看它们是否相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.