Abinash Sinha
Abinash Sinha

Reputation: 840

Google URL shortening API not working in Java

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.

I have used the following 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;
        }
    }

}

Need suggestions.

Upvotes: 2

Views: 5129

Answers (2)

The thing you are trying to achieve can be done by the following code. This code would directly allow you to use the Google URL shortening web service

     public static String shortenUrl(String longUrl)
   {
        @SuppressWarnings("unused")
        OAuthService oAuthService = new ServiceBuilder().provider(GoogleApi.class).apiKey("anonymous").apiSecret("anonymous")
                        .scope("https://www.googleapis.com/auth/urlshortener") .build();
        OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, "https://www.googleapis.com/urlshortener/v1/url");
        oAuthRequest.addHeader("Content-Type", "application/json");
        String json = "{\"longUrl\": \"http://"+longUrl+"/\"}";
        oAuthRequest.addPayload(json);
        Response response = oAuthRequest.send();
        Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
        Map<String, String> responseMap = new GsonBuilder().create().fromJson(response.getBody(), typeOfMap);
        String st=responseMap.get("id");
        return st;
    }

You have to make some changes in your original code and you are done..

Upvotes: 2

ikumen
ikumen

Reputation: 11663

Google URL shortener has an API - which allows for programmatic interaction - but you'll need to authenticate before using it. Authentication is via Oauth - I recommend using Scribe.

Upvotes: 1

Related Questions