IntentConverterの開発 2

Google Readerから渡されるURLが長いので、TinyURLでURL短縮する。


    public static String shortenUrl(String urlStr) {
    	String shortenedUrlStr = urlStr;

    	String shorterServiceUrtStr = "http://tinyurl.com/api-create.php?url=";
    	HttpURLConnection connection = null;
    	InputStream is = null;
    	byte[] buffer = null;
    	ByteArrayOutputStream baos = null;

    	try {
    		URL url = new URL(shorterServiceUrtStr + urlStr);
    		connection = (HttpURLConnection)url.openConnection();
    		connection.setRequestMethod("GET");
    		connection.connect();
    		is = connection.getInputStream();
    		baos = new ByteArrayOutputStream();
    		buffer = new byte[256];
    		int len = is.read(buffer);
    		while (len > 0) {
    			baos.write(buffer, 0, len);
    			len = is.read(buffer);
    		}
    		baos.close();
    		is.close();

        	shortenedUrlStr = baos.toString();
    	} catch (Exception e) {
    		if (baos != null) {
    			try {
    				baos.close();
    			} catch (IOException ioe) {

    			}
    		}
    		if (is != null) {
    			try {
    				is.close();
    			} catch (IOException ioe) {

    			}
    		}
    	}

    	return shortenedUrlStr;
    }

■参考