Skip to content Skip to sidebar Skip to footer

Grabbing Json Works From One Link, Not From Another

I'm doing a simple JSON grab from two links with the same code. I'm doing it two separate times, so the cause of my issue isn't because they're running into each other or something

Solution 1:

Log this: int contentLength = connection.getContentLength();

I don't see the google url returning a content-length header.

If you just want String output from a url, you can use Scanner and URL like so:

Scanner s = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A");
out = s.next();
s.close();

(don't forget try/finally block and exception handling)

The longer way (which allows for progress reporting and such):

String convertStreamToString(InputStream is)throws UnsupportedEncodingException {

      BufferedReaderreader=newBufferedReader(newInputStreamReader(is, "UTF-8"));
      StringBuildersb=newStringBuilder();
      Stringline=null;
      try {
          while ((line = reader.readLine()) != null)
              sb.append(line + "\n");
      } catch (IOException e) {
          // Handle exception
      } finally {
          try {
              is.close();
          } catch (IOException e) {
              // Handle exception
          }
      }
      return sb.toString();
   }
}

and then call String response = convertStreamToString( inputStream );

Post a Comment for "Grabbing Json Works From One Link, Not From Another"