short-urlgoogle-url-shortener

Google URL Shortener API: Converting a long URL to short


I want to convert a long URL into short one.
I have followed the documentation, but I'm not able to convert the URL.
It's resulting in 403 response.

I followed below aproach.

        JSONObject reqObj = new JSONObject();
        reqObj.put("longUrl", LONG_URL_TO_CONVERT);
        reqObj.put("key", API_KEY);

        URL url = new URL("https://www.googleapis.com/urlshortener/v1/url");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(reqObj.toString().getBytes());

        InputStream inputStream = conn.getInputStream();
        String resp = readStream(inputStream);

I tried with GET request
https://www.googleapis.com/urlshortener/v1/url?key=API_KEY&longUrl=www.google.com
but it's returning an error message Required parameter: shortUrl

What I'm doing wrong here ?


Solution

  • Finally found the solution.
    Instead of adding key as a post param, appended it to the URL itself. like
    https://www.googleapis.com/urlshortener/v1/url?key={API_KEY}
    and it worked as expected.