我有一个太长的链接(有一些网址参数等)。我想用googpe API urlshortener来缩短这个时间。API-key是在google开发者控制台中创建的。密钥是“公共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
发布于 2015-02-03 22:51:34
我想可能是我的HTTP请求出了问题。当我使用这里使用的代码:http://www.snip2code.com/Snippet/216067/Call-Google-Shorten-URL-API时,它起作用了。
发布这个答案而不是删除问题,因为API是最近更改的(我猜是2014年中),所以没有太多的更新示例。
祝所有尝试访问此API的人好运:)
https://stackoverflow.com/questions/28301056
复制相似问题