How do I use the Google URL Shortener API on Android?

12.4k views Asked by At

After much fiddling with trying to import the libraries myself, I finally managed to find out that I can do so using the Google Plugin for Eclipse, here.

However, I seem to be unable to find any examples of how to actually use the API on Android, at least none that are compilable, as the classes required in those examples seem to not be resolvable by Eclipse, so I can only assume that these classes do not exist in the libraries that are imported by the Google Plugin for Eclipse for the URL Shortener API. The closest thing to an example I could find is here, which appears to be for Google App Engine, not Android, and uses classes that I cannot seem to get access to.

So the question is, how do I use this API to get a shortened version of a URL, in an Android application? Preferably, I would like to do it using an API Key, instead of OAuth.

4

There are 4 answers

5
babay On
  1. add to your manifest in application node:
 <meta-data
         android:name="com.google.android.urlshortener.API_KEY"
         android:value="{YOUR_API_KEY}"/>
  1. add folowing libraries:

google-api-client-1.17.0-rc.jar

google-api-client-android-1.17.0-rc.jar

google-api-services-urlshortener-v1-rev22-1.17.0-rc.jar

google-http-client-1.17.0-rc.jar

google-http-client-android-1.17.0-rc.jar

  1. method:

       String shorten(String longUrl){
    
       Urlshortener.Builder builder = new Urlshortener.Builder (AndroidHttp.newCompatibleTransport(), AndroidJsonFactory.getDefaultInstance(), null);
       Urlshortener urlshortener = builder.build();
    
        com.google.api.services.urlshortener.model.Url url = new Url();
        url.setLongUrl(longUrl);
        try {
           url = urlshortener.url().insert(url).execute();
            return url.getId();
        } catch (IOException e) {
            return null;
       }
    }
    
0
sivi On

You can also use gradle apparently

repositories {
mavenCentral()
}

dependencies {
compile 'com.google.apis:google-api-services-urlshortener:v1-rev47-1.22.0'
}

Google Shortner java gradle documentation

2
Satish Silveri On

First create a project on google console and enable url shortner api and get api key and the use the following Asynctask to get shortened url.

 public class newShortAsync extends AsyncTask<Void,Void,String> {

        String longUrl="http://stackoverflow.com/questions/18372672/how-do-i-use-the-google-url-shortener-api-on-android/20406915";
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
         }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressBar.setVisibility(View.GONE);
            System.out.println("JSON RESP:" + s);
            String response=s;
            try {
                JSONObject jsonObject=new JSONObject(response);
                id=jsonObject.getString("id");
                System.out.println("ID:"+id);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected String doInBackground(Void... params) {
            BufferedReader reader;
            StringBuffer buffer;
            String res=null;
            String json = "{\"longUrl\": \""+longUrl+"\"}";
            try {
                URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?key=YOUR_API_KEY");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setReadTimeout(40000);
                con.setConnectTimeout(40000);
                con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "application/json");
                OutputStream os = con.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));

                writer.write(json);
                writer.flush();
                writer.close();
                os.close();

                int status=con.getResponseCode();
                InputStream inputStream;
                if(status==HttpURLConnection.HTTP_OK)
                inputStream=con.getInputStream();
                else
                    inputStream = con.getErrorStream();

                reader= new BufferedReader(new InputStreamReader(inputStream));

                buffer= new StringBuffer();

                String line="";
                while((line=reader.readLine())!=null)
                {
                    buffer.append(line);
                }

                res= buffer.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return res;




        }
    }

and then just execute this asynctask you will get a json responce in which id is present which is nothing but shortened Url.

0
Liu Ocean On

Now the Google shorter api needs key to work. I tried set key in manifest but it's not working. Key should be set by function library.

Urlshortener.Builder builder = new Urlshortener.Builder (AndroidHttp.newCompatibleTransport(),
            AndroidJsonFactory.getDefaultInstance(), null);
    Urlshortener urlshortener = builder.build();

    com.google.api.services.urlshortener.model.Url url = new com.google.api.services.urlshortener.model.Url();
    url.setLongUrl(longUrl);
    try {
        Urlshortener.Url.Insert insert=urlshortener.url().insert(url);
        insert.setKey("Your API KEY");
        url = insert.execute();
        return url.getId();
    } catch (IOException e) {
        LogUtil.e(TAG, Log.getStackTraceString(e));
        return null;
    }