27

This method returns the source of the given URL.

private static String getUrlSource(String url) {
    try {
        URL localUrl = null;
        localUrl = new URL(url);
        URLConnection conn = localUrl.openConnection();
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
        String line = "";
        String html;
        StringBuilder ma = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            ma.append(line);
        }
        return ma;
    } catch (Exception e) {
        Log.e("ERR",e.getMessage());
    }
}

It gives me this error:

Type mismatch: cannot convert from StringBuilder to String

And two choices:

  1. Change the return type to StringBuilder. But I want it to return a String.
  2. Change type of ma to String. After changing a String has no append() method.
2
  • 6
    return ma.toString(); ??? Commented Apr 22, 2013 at 20:09
  • As a side note, you might want to ma.append(line).append(LINE_SEPERATOR) or your lines will be all garbled like This is line 1.This is line 2.This is line 3. Commented Apr 22, 2013 at 20:12

3 Answers 3

54

Just use

return ma.toString();

instead of

return ma;

ma.toString() returns the string representation for your StringBuilder.

See StringBuilder#toString() for details

As Valeri Atamaniouk suggested in comments, you should also return something in the catch block, otherwise you will get a compiler error for missing return statement, so editing

} catch (Exception e) {
    Log.e("ERR",e.getMessage());
}

to

} catch (Exception e) {
    Log.e("ERR",e.getMessage());
    return null; //or maybe return another string
}

Would be a good idea.


EDIT

As Esailija suggested, we have three anti-patterns in this code

} catch (Exception e) {           //You should catch the specific exception
    Log.e("ERR",e.getMessage());  //Don't log the exception, throw it and let the caller handle it
    return null;                  //Don't return null if it is unnecessary
}

So i think it is better to do something like that:

private static String getUrlSource(String url) throws MalformedURLException, IOException {
    URL localUrl = null;
    localUrl = new URL(url);
    URLConnection conn = localUrl.openConnection();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
    String line = "";
    String html;
    StringBuilder ma = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        ma.append(line);
    }
    return ma.toString();
}

And then, when you call it:

try {
    String urlSource = getUrlSource("http://www.google.com");
    //process your url source
} catch (MalformedURLException ex) {
    //your url is wrong, do some stuff here
} catch (IOException ex) {
    //I/O operations were interrupted, do some stuff here
}

Check these links for further details about Java Anti-Patterns:

Sign up to request clarification or add additional context in comments.

3 Comments

Function must also return a value in case of exception. If you haven't noticed.
@ValeriAtamaniouk Yes they do sometimes, but that's outside the scope of the question. It would make a great comment for the OP, though, like my advice on adding line separators.
swallowing exception, logging it and returning null - all 3 antipatterns at the same time. Impressive.
3

I have same problem while converting StringBuilder to String, and i use above point but that's not give correct solution. using above code output comes like this

    String out=ma.toString();
// out=[Ljava.lang.String;@41e633e0

After that i find out correct solution.Think is create a new String instant inserted of StringBuilder like this..

String out=new String(ma);

Comments

0

try

return ma.toString(); as you can not directly store stringbuilder variable into a string variable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.