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

我有一个太长的链接(有一些 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 的人好运 :)

https://stackoverflow.com/questions/28301056/

相关文章:

url - 跟踪为长 URL 生成的短 URL

short-url - 生成多个唯一的短网址?

c# - 字符串加密并缩短到更小的长度

short-url - 如何获得 goo.gl 分析?

php - 无法让 PHP 代码工作

php - 动态php短网址

dns - 如何获取我的网站的短网址?

url - 为什么在某些国家/地区拒绝使用短网址是这种犯罪?

php - 网址缩短 : using inode as short name?

google-app-engine - 使用 Google App Engine 生成带有实体键的短