Java URL Connection shortenUrl(String url)

Here you can find the source of shortenUrl(String url)

Description

shorten Url

License

Apache License

Declaration

private static String shortenUrl(String url) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Main {
    private static String shortenUrl(String url) {
        String shortUrl = "";

        try {//from www .  j ava2s .c  o  m
            URLConnection conn = new URL("https://www.googleapis.com/urlshortener/v1/url").openConnection();
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json");
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write("{\"longUrl\":\"" + url + "\"}");
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;

            while ((line = rd.readLine()) != null) {
                if (line.indexOf("id") > -1) {
                    //hack
                    shortUrl = line.substring(8, line.length() - 2);
                    break;
                }
            }

            wr.close();
            rd.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return shortUrl;

    }
}

Related

  1. sendGetRequest(String resourceUrl, String contentType)
  2. sendGetRequest(String urlStr)
  3. sendPost(String url, String param)
  4. setTimeout(URLConnection conn, int milliseconds)
  5. setTimeouts(URLConnection connection)
  6. skip(URLConnection connection, long count)
  7. slurpStream(URLConnection conn)
  8. slurpURL(URL u, String encoding)
  9. slurpURLNoExceptions(URL u)