001package com.nimbusds.jose.util; 002 003 004import java.io.IOException; 005import java.io.InputStream; 006import java.net.URL; 007import java.net.URLConnection; 008 009import org.apache.commons.io.IOUtils; 010import org.apache.commons.io.input.BoundedInputStream; 011 012 013/** 014 * URL utilities. 015 * 016 * @author Vladimir Dzhuvinov 017 * @version $version$ (2014-12-14) 018 */ 019public class URLUtils { 020 021 022 /** 023 * Reads the content of the specified URL. 024 * 025 * @param url The URL content. Must not be {@code null}. 026 * @param connectTimeout The URL connection timeout, in milliseconds. 027 * If zero no (infinite) timeout. 028 * @param readTimeout The URL read timeout, in milliseconds. If zero 029 * no (infinite) timeout. 030 * @param sizeLimit The read size limit, in bytes. If negative no 031 * limit. 032 * 033 * @return The content. 034 * 035 * @throws IOException If the URL content couldn't be read. 036 */ 037 public static String read(final URL url, 038 final int connectTimeout, 039 final int readTimeout, 040 final int sizeLimit) 041 throws IOException { 042 043 URLConnection conn = url.openConnection(); 044 045 conn.setConnectTimeout(connectTimeout); 046 conn.setReadTimeout(readTimeout); 047 048 InputStream inputStream = conn.getInputStream(); 049 050 if (sizeLimit > 0) { 051 inputStream = new BoundedInputStream(inputStream, sizeLimit); 052 } 053 054 try { 055 return IOUtils.toString(inputStream); 056 057 } finally { 058 059 IOUtils.closeQuietly(inputStream); 060 } 061 } 062}