Question

When using the Goo.gl API is there a way to tell it not to automatically add a trailing slash? Because it messes up a lot of website, for example if you go to: http://www.samsung.com/us/support/SupportOwnersFAQPopup.do?faq_id=FAQ00046726&fm_seq=49755 with a trailing slash it doesn't work! Any suggestions?

My Code:

  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();
            }
Was it helpful?

Solution

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

You're adding the slash after the longurl yourself, goo.gl isn't doing it.

OTHER TIPS

Also consider using a library I made that provide a nice interface to shorten your urls using Goo.gl service.

It supports the api key and is very easy to use:

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!
}

Take a look at the github repo here which contains further infos :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top