List of usage examples for java.net URLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:net.technicpack.rest.RestObject.java
public static <T extends RestObject> T getRestObject(Class<T> restObject, String url) throws RestfulAPIException { InputStream stream = null;/*from ww w.j av a2 s . c o m*/ try { URLConnection conn = new URL(url).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); conn.setConnectTimeout(15000); conn.setReadTimeout(15000); stream = conn.getInputStream(); String data = IOUtils.toString(stream, Charsets.UTF_8); T result = gson.fromJson(data, restObject); if (result == null) { throw new RestfulAPIException("Unable to access URL [" + url + "]"); } if (result.hasError()) { throw new RestfulAPIException("Error in response: " + result.getError()); } return result; } catch (SocketTimeoutException e) { throw new RestfulAPIException("Timed out accessing URL [" + url + "]", e); } catch (MalformedURLException e) { throw new RestfulAPIException("Invalid URL [" + url + "]", e); } catch (JsonParseException e) { throw new RestfulAPIException("Error parsing response JSON at URL [" + url + "]", e); } catch (IOException e) { throw new RestfulAPIException("Error accessing URL [" + url + "]", e); } finally { IOUtils.closeQuietly(stream); } }
From source file:org.apache.niolex.commons.net.HTTPUtil.java
/** * Do the HTTP request.//from w ww.ja va 2 s. c om * * @param strUrl the request URL * @param params the request parameters * @param paramCharset the charset used to send the request parameters * @param headers the request headers * @param connectTimeout the connection timeout * @param readTimeout the data read timeout * @param useGet whether do we use the HTTP GET method * @return the response pair; a is response header map, b is response body * @throws NetException */ public static final Pair<Map<String, List<String>>, byte[]> doHTTP(String strUrl, Map<String, String> params, String paramCharset, Map<String, String> headers, int connectTimeout, int readTimeout, boolean useGet) throws NetException { LOG.debug("Start HTTP {} request to [{}], C{}R{}.", useGet ? "GET" : "POST", strUrl, connectTimeout, readTimeout); InputStream in = null; try { // 1. For get, we pass parameters in URL; for post, we save it in reqBytes. byte[] reqBytes = null; if (!CollectionUtil.isEmpty(params)) { if (useGet) { strUrl = strUrl + '?' + prepareWwwFormUrlEncoded(params, paramCharset); } else { reqBytes = StringUtil.strToAsciiByte(prepareWwwFormUrlEncoded(params, paramCharset)); } } URL url = new URL(strUrl); // We use Java URL to do the HTTP request. URLConnection ucon = url.openConnection(); ucon.setConnectTimeout(connectTimeout); ucon.setReadTimeout(readTimeout); // 2. validate to Connection type. if (!(ucon instanceof HttpURLConnection)) { throw new NetException(NetException.ExCode.INVALID_URL_TYPE, "The request is not in HTTP protocol."); } final HttpURLConnection httpCon = (HttpURLConnection) ucon; // 3. We add all the request headers. if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpCon.addRequestProperty(entry.getKey(), entry.getValue()); } } // 4. For get or no parameter, we do not output data; for post, we pass parameters in Body. if (reqBytes == null) { httpCon.setDoOutput(false); } else { httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpCon.setRequestProperty("Content-Length", Integer.toString(reqBytes.length)); httpCon.setRequestMethod("POST"); httpCon.setDoOutput(true); } httpCon.setDoInput(true); httpCon.connect(); // 5. do output if needed. if (reqBytes != null) { StreamUtil.writeAndClose(httpCon.getOutputStream(), reqBytes); } // 6. Get the input stream. in = httpCon.getInputStream(); final int contentLength = httpCon.getContentLength(); validateHttpCode(strUrl, httpCon); byte[] ret = null; // 7. Read response byte array according to the strategy. if (contentLength > 0) { ret = commonDownload(contentLength, in); } else { ret = unusualDownload(strUrl, in, MAX_BODY_SIZE, true); } // 8. Parse the response headers. LOG.debug("Succeeded to execute HTTP request to [{}], response size {}.", strUrl, ret.length); return Pair.create(httpCon.getHeaderFields(), ret); } catch (NetException e) { LOG.info(e.getMessage()); throw e; } catch (Exception e) { String msg = "Failed to execute HTTP request to [" + strUrl + "], msg=" + e.toString(); LOG.warn(msg); throw new NetException(NetException.ExCode.IOEXCEPTION, msg, e); } finally { // Close the input stream. StreamUtil.closeStream(in); } }
From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java
public static File downloadTM(final String url, final String authUrl, final String username, final String password, final int timeout) throws IOException { InputStream in = null;/*from w ww .j a v a 2s. c om*/ OutputStream out = null; try { final URL u = new URL(url); final URLConnection urlc = u.openConnection(); if (timeout != 0) { urlc.setConnectTimeout(timeout); urlc.setReadTimeout(timeout); } if (urlc instanceof HttpsURLConnection) { final String cookie = getTmCookie(authUrl, username, password, timeout).toString(); final HttpsURLConnection http = (HttpsURLConnection) urlc; http.setInstanceFollowRedirects(false); http.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(final String arg0, final SSLSession arg1) { return true; } }); http.setRequestMethod(GET_STR); http.setAllowUserInteraction(true); http.addRequestProperty("Cookie", cookie); } in = urlc.getInputStream(); final File outputFile = File.createTempFile(tmpPrefix, tmpSuffix); out = new FileOutputStream(outputFile); IOUtils.copy(in, out); return outputFile; } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
From source file:net.technicpack.rest.RestObject.java
public static <T> List<T> getRestArray(Class<T> restObject, String url) throws RestfulAPIException { InputStream stream = null;//from w w w .j a v a 2 s .co m try { URLConnection conn = new URL(url).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); conn.setConnectTimeout(15000); conn.setReadTimeout(15000); stream = conn.getInputStream(); String data = IOUtils.toString(stream, Charsets.UTF_8); JsonElement response = gson.fromJson(data, JsonElement.class); if (response == null || !response.isJsonArray()) { if (response.isJsonObject() && response.getAsJsonObject().has("error")) throw new RestfulAPIException("Error in response: " + response.getAsJsonObject().get("error")); else throw new RestfulAPIException("Unable to access URL [" + url + "]"); } JsonArray array = response.getAsJsonArray(); List<T> result = new ArrayList<T>(array.size()); for (JsonElement element : array) { if (element.isJsonObject()) result.add(gson.fromJson(element.getAsJsonObject(), restObject)); else result.add(gson.fromJson(element.getAsString(), restObject)); } return result; } catch (SocketTimeoutException e) { throw new RestfulAPIException("Timed out accessing URL [" + url + "]", e); } catch (MalformedURLException e) { throw new RestfulAPIException("Invalid URL [" + url + "]", e); } catch (JsonParseException e) { throw new RestfulAPIException("Error parsing response JSON at URL [" + url + "]", e); } catch (IOException e) { throw new RestfulAPIException("Error accessing URL [" + url + "]", e); } finally { IOUtils.closeQuietly(stream); } }
From source file:com.arcusys.liferay.vaadinplugin.util.ControlPanelPortletUtil.java
/** * Downloads the given URL to the targetDir and names it * {@code targetFilename}. Creates the directory and its parent(s) if it * does not exist./* ww w .j av a 2 s . com*/ * * @param downloadUrl * @param targetDir * @param targetFilename * @throws IOException */ public static void download(String downloadUrl, String targetDir, String targetFilename) throws IOException { File f = new File(targetDir); f.mkdirs(); URL url = new URL(downloadUrl); URLConnection conn = url.openConnection(); conn.setConnectTimeout(10000); InputStream is = conn.getInputStream(); FileOutputStream out = new FileOutputStream(new File(targetDir, targetFilename)); IOUtils.copy(is, out); close(out); close(is); }
From source file:org.apache.maven.report.projectinfo.ProjectInfoReportUtils.java
/** * @param url not null//from w w w . j a v a 2s. co m * @param project not null * @param settings not null * @return the url connection with auth if required. Don't check the certificate if SSL scheme. * @throws IOException if any */ private static URLConnection getURLConnection(URL url, MavenProject project, Settings settings) throws IOException { URLConnection conn = url.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); // conn authorization if (settings.getServers() != null && !settings.getServers().isEmpty() && project != null && project.getDistributionManagement() != null && (project.getDistributionManagement().getRepository() != null || project.getDistributionManagement().getSnapshotRepository() != null) && (StringUtils.isNotEmpty(project.getDistributionManagement().getRepository().getUrl()) || StringUtils.isNotEmpty( project.getDistributionManagement().getSnapshotRepository().getUrl()))) { Server server = null; if (url.toString().contains(project.getDistributionManagement().getRepository().getUrl())) { server = settings.getServer(project.getDistributionManagement().getRepository().getId()); } if (server == null && url.toString() .contains(project.getDistributionManagement().getSnapshotRepository().getUrl())) { server = settings.getServer(project.getDistributionManagement().getSnapshotRepository().getId()); } if (server != null && StringUtils.isNotEmpty(server.getUsername()) && StringUtils.isNotEmpty(server.getPassword())) { String up = server.getUsername().trim() + ":" + server.getPassword().trim(); String upEncoded = new String(Base64.encodeBase64Chunked(up.getBytes())).trim(); conn.setRequestProperty("Authorization", "Basic " + upEncoded); } } if (conn instanceof HttpsURLConnection) { HostnameVerifier hostnameverifier = new HostnameVerifier() { /** {@inheritDoc} */ public boolean verify(String urlHostName, SSLSession session) { return true; } }; ((HttpsURLConnection) conn).setHostnameVerifier(hostnameverifier); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { /** {@inheritDoc} */ public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } /** {@inheritDoc} */ public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } /** {@inheritDoc} */ public X509Certificate[] getAcceptedIssuers() { return null; } } }; try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory); } catch (NoSuchAlgorithmException e1) { // ignore } catch (KeyManagementException e) { // ignore } } return conn; }
From source file:AnimatedMetadataGraph.java
public static JSONObject getAllResources(URL sfsUrl) { if (sfsUrl != null) { try {/*from www . j a v a2s . c om*/ URL sfsGetRsrcsUrl = new URL(sfsUrl.toString() + "/admin/listrsrcs/"); URLConnection smapConn = sfsGetRsrcsUrl.openConnection(); smapConn.setConnectTimeout(5000); smapConn.connect(); //GET reply BufferedReader reader = new BufferedReader(new InputStreamReader(smapConn.getInputStream())); StringBuffer lineBuffer = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) lineBuffer.append(line); line = lineBuffer.toString(); reader.close(); return (JSONObject) JSONSerializer.toJSON(line); } catch (Exception e) { logger.log(Level.WARNING, "", e); return null; } } return null; }
From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java
public static String fetchContent(final URLConnection conn, final int timeout) throws IOException { conn.setAllowUserInteraction(true);/* ww w . jav a2 s. c o m*/ if (timeout != 0) { conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); } conn.connect(); return IOUtils.toString(new InputStreamReader(conn.getInputStream(), UTF8_STR)); }
From source file:AnimatedMetadataGraph.java
public static JSONArray getChildren(URL sfsUrl, String path) { if (sfsUrl != null) { try {//w ww. ja v a 2 s . c om URL sfsGetRsrcsUrl = new URL(sfsUrl.toString() + path); URLConnection smapConn = sfsGetRsrcsUrl.openConnection(); smapConn.setConnectTimeout(5000); smapConn.connect(); //GET reply BufferedReader reader = new BufferedReader(new InputStreamReader(smapConn.getInputStream())); StringBuffer lineBuffer = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) lineBuffer.append(line); line = lineBuffer.toString(); reader.close(); JSONObject resp = (JSONObject) JSONSerializer.toJSON(line); return resp.optJSONArray("children"); } catch (Exception e) { logger.log(Level.WARNING, "", e); return null; } } return null; }
From source file:savant.util.NetworkUtils.java
/** * Open a stream for the given URL with the CONNECT_TIMEOUT and READ_TIMEOUT. * @throws IOException//from w w w. ja v a 2 s. co m */ public static InputStream openStream(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); return conn.getInputStream(); }