我有以下使用谷歌 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;
}
}
}
需要建议。