我有一个太长的链接(有一些 URL 参数等)。我想使用 googpe API urlshortener 缩短它。API 密钥是在谷歌开发者控制台中创建的。密钥是“公共 API 访问”和“服务器应用程序密钥”。谁能看到为什么这段代码不起作用?我已经尝试了太长时间来实现这一点。
try {
String g = "https://www.googleapis.com/urlshortener/v1/url";
String url = g + "?key=secretKey";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// add header
//post.setHeader("User-Agent", USER_AGENT);
post.setHeader("Accept", "application/json");
//add the long url as a parameter
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("longUrl", "www.google.com"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
} } catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
返回响应码 400