我想将长 URL 转换为短 URL。
我已按照文档进行操作,但无法转换 URL。
这会导致 403 响应。
我遵循以下方法。
JSONObject reqObj = new JSONObject();
reqObj.put("longUrl", LONG_URL_TO_CONVERT);
reqObj.put("key", API_KEY);
URL url = new URL("https://www.googleapis.com/urlshortener/v1/url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
outputStream.write(reqObj.toString().getBytes());
InputStream inputStream = conn.getInputStream();
String resp = readStream(inputStream);
我尝试了 GET 请求
https://www.googleapis.com/urlshortener/v1/url?key=API_KEY&longUrl=www.google.com
但它返回一条错误消息 Required parameter: shortUrl
我在这里做错了什么?
最佳答案
终于找到解决办法了。
不是将 key 添加为 post 参数,而是将其附加到 URL 本身。喜欢
https://www.googleapis.com/urlshortener/v1/url?key= {API_KEY}
它按预期工作。
关于short-url - 谷歌 URL 缩短 API : Converting a long URL to short,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40146500/