簡體   English   中英

如何比較兩個用於URL的字符串

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM