Goo.gl API自动添加尾部斜杠

时间:2012-07-16 19:14:45

标签: java android goo.gl

使用Goo.gl API时有没有办法告诉它不要自动添加尾部斜杠?因为它弄乱了很多网站,例如,如果你带着尾随斜线转到:http://www.samsung.com/us/support/SupportOwnersFAQPopup.do?faq_id=FAQ00046726&fm_seq=49755它不起作用!有什么建议吗?

我的代码:

  address= "https://www.googleapis.com/urlshortener/v1/url?key=xxxxxxxxxxxxx"
  DefaultHttpClient client = new DefaultHttpClient();
  HttpPost post = new HttpPost(address);
           try {
                post.setEntity(new StringEntity("{\"longUrl\": \"" +longurl+ "/\"}"));
                post.setHeader("Content-Type", "application/json"); 
                if (userLogin == true) {
                    post.setHeader("Authorization", "OAuth "+accessToken);
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            try {
                org.apache.http.HttpResponse response = client.execute(post);
                String responseBody = EntityUtils.toString(response.getEntity());
                JSONObject object = (JSONObject) new JSONTokener(responseBody).nextValue();
                query = object.getString("id");
                shortUrl = query;
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

2 个答案:

答案 0 :(得分:4)

post.setEntity(new StringEntity("{\"longUrl\": \"" +longurl+ "/\"}"));
// I think I found the problem -------------------------------^ 

你自己在longurl之后添加斜杠,goo.gl没有这样做。

答案 1 :(得分:0)

另外考虑使用我制作的库,它提供了一个很好的界面,可以使用Goo.gl服务缩短您的网址。

它支持api密钥,并且非常易于使用:

GoogleShortenerPerformer shortener = new GoogleShortenerPerformer(new OkHttpClient());

String longUrl = "http://www.andreabaccega.com/";

GooglShortenerResult result = shortener.shortenUrl(
    new GooglShortenerRequestBuilder()
        .buildRequest(longUrl)
    );
if ( Status.SUCCESS.equals(result.getStatus()) ) {
    // all ok result.getShortenedUrl() contains the shortened url!
}

查看包含更多信息的github repo here:)