Google URL缩短API无法在Java中运行

时间:2013-07-30 04:34:52

标签: java json google-url-shortener

我有以下使用谷歌URL缩短服务的代码。代码运行得很好但它返回一个URL,将我重定向到谷歌登录页面。有没有办法通过我的代码登录谷歌帐户,然后使用缩短服务或直接获得缩短的URL。

我使用了以下代码:

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;
        }
    }

}

需要建议。

2 个答案:

答案 0 :(得分:2)

您尝试实现的目标可以通过以下代码完成。此代码将直接允许您使用Google网址缩短网络服务

     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;
    }

您必须对原始代码进行一些更改才能完成..

答案 1 :(得分:1)

Google URL shortener has an API - 允许程序化交互 - 但在使用之前您需要进行身份验证。身份验证是通过Oauth进行的 - 我建议使用Scribe