我试图在不使用外部库的情况下在 Java 中执行此操作。我不能使用外部库来执行此操作,因为我没有在这个项目中使用 Maven。
我使用的方法是:
public static String shorten(String longUrl) {
if (longUrl == null) {
return longUrl;
}
StringBuilder sb = null;
String line = null;
String urlStr = longUrl;
try {
URL url = new URL("https://www.googleapis.com/urlshortener/v1/url");
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(urlStr, "UTF-8"));
writer.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
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) {
e.printStackTrace();
return longUrl;
} catch (IOException e) {
e.printStackTrace();
return longUrl;
}
}
我得到的错误是:
[23:30:44 WARN]: java.io.IOException: Server returned HTTP response code: 400 for URL: https://www.googleapis.com/urlshortener/v1/url
[23:30:44 WARN]: at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1838)
[23:30:44 WARN]: at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
[23:30:44 WARN]: at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
如果此方法不起作用,是否有一些不需要外部 jar 的简单 Java URL 缩短替代方案?谢谢您的帮助!
编辑
api 的 url 错误。也用新的错误更新了它。