gpt4 book ai didi

java - google-api-client 在 java 中创建短 URL

转载 作者:bug小助手 更新时间:2023-10-28 01:29:24 27 4
gpt4 key购买 nike

我有一个太长的链接(有一些 URL 参数等)。我想使用 googpe API urlshortener 缩短它。API key 是在谷歌开发者控制台中创建的。 key 是“公共(public) API 访问”和“服务器应用程序 key ”。谁能看到为什么这段代码不起作用?我已经尝试了太长时间来实现这一点。

 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

最佳答案

我猜我的 HTTP 请求有问题。当我使用这里使用的代码时:http://www.snip2code.com/Snippet/216067/Call-Google-Shorten-URL-API成功了。

发布这个答案而不是仅仅删除问题,因为 API 最近发生了变化(我猜是 2014 年年中),所以没有太多更新的例子。

祝所有尝试访问此 API 的人好运 :)

关于java - google-api-client 在 java 中创建短 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28301056/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com