title: Google URL shortening API not working in Java
body: <p>I have the following code which uses google URL shortening service. The code runs just fine but it returns a URL which redirects me to google login page. Is there a way to login google account through my code and then use the shortening service or directly get the shortened URL. </p>
  
  <p>I have used the following code:</p>
  
  <pre><code>public static String shorten(String longUrl) {
          if (longUrl == null) {
              return longUrl;
          }
  
          try {
              URL url = new URL("http://goo.gl/");
              HttpURLConnection connection = (HttpURLConnection) url.openConnection();
              connection.setDoOutput(true);
              connection.setRequestMethod("POST");
              connection.setRequestProperty("User-Agent", "toolbar");
  
              OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
              writer.write("url=" + URLEncoder.encode(longUrl, "UTF-8"));
              writer.close();
  
              BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
              StringBuilder sb = new StringBuilder();
              String line = null;
              while ((line = rd.readLine()) != null) {
                  sb.append(line + '\n');
              }
              String json = sb.toString();
              return json.substring(json.indexOf("http"), json.indexOf("\"", json.indexOf("http")));
          } catch (MalformedURLException e) {
              return longUrl;
          } catch (IOException e) {
              e.printStackTrace();
              return longUrl;
          }
      }
  
  }
  </code></pre>
  
  <p>Need suggestions.</p>