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

牧云@^-^@ 提交于 2019-11-27 20:54:50

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.

babay
  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;
       }
    }
    

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!