Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 483
Ogre Avatar asked Aug 22 '13 05:08

Ogre


People also ask

How do you shorten a URL on Android?

Google URL Shortener All you have to do is copy and paste your URL into the space that says “Your original URL here.” Then you click “I'm not a Robot” so that Google knows that you're real. Finally, click the “Shorten URL” button. Google then spits out your new and improved URL and you're ready to go.

How do I use Google shortener?

Simply visit goo.gl, sign-in and then create a shortened link by pasting your target URL into the box and clicking the SHORTEN URL button. This will generate your shortened link and add it to your library of previous ones. If playback doesn't begin shortly, try restarting your device.

How do I get a Google URL shortener API key?

- Go to the [url=https://console.developers.google.com/]Google Developers Console[/url]. - Select a project, or create a new one. - In the sidebar on the left, expand APIs & auth. Next, click APIs.

How do I shorten an API URL?

Bitly allows users to shorten URLs, share, and track links. Bitly's Function can be accessed through their website, bookmarklets, and this open API . The Bit.ly service enables users to customize shortened links using their brand names or other words.


3 Answers

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.

like image 65
Satish Silveri Avatar answered Nov 14 '22 22:11

Satish Silveri


  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;
       }
    }
    
like image 27
babay Avatar answered Nov 14 '22 22:11

babay


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;
    }
like image 42
Liu Ocean Avatar answered Nov 14 '22 23:11

Liu Ocean