List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:Main.java
public static String callJsonAPI(String urlString) { // Use HttpURLConnection as per Android 6.0 spec, instead of less efficient HttpClient HttpURLConnection urlConnection = null; StringBuilder jsonResult = new StringBuilder(); try {/* w w w.ja v a 2 s .c o m*/ URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(TIMEOUT_CONNECTION); urlConnection.setReadTimeout(TIMEOUT_READ); urlConnection.connect(); int status = urlConnection.getResponseCode(); switch (status) { case 200: case 201: BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = br.readLine()) != null) { jsonResult.append(line).append("\n"); } br.close(); } } catch (MalformedURLException e) { System.err.print(e.getMessage()); return e.getMessage(); } catch (IOException e) { System.err.print(e.getMessage()); return e.getMessage(); } finally { if (urlConnection != null) { try { urlConnection.disconnect(); } catch (Exception e) { System.err.print(e.getMessage()); } } } return jsonResult.toString(); }
From source file:de.Keyle.MyPet.api.Util.java
public static String readUrlContent(String address, int timeout) throws IOException { StringBuilder contents = new StringBuilder(2048); BufferedReader br = null;/*from w w w .jav a2 s. c o m*/ try { URL url = new URL(address); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setConnectTimeout(timeout); huc.setReadTimeout(timeout); huc.setRequestMethod("GET"); huc.connect(); br = new BufferedReader(new InputStreamReader(huc.getInputStream())); String line; while ((line = br.readLine()) != null) { contents.append(line); } } finally { try { if (br != null) { br.close(); } } catch (Exception e) { e.printStackTrace(); } } return contents.toString(); }
From source file:com.magnet.plugin.helpers.URLHelper.java
public static InputStream loadUrl(final String url) throws Exception { final InputStream[] inputStreams = new InputStream[] { null }; final Exception[] exception = new Exception[] { null }; Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { try { HttpURLConnection connection; if (ApplicationManager.getApplication() != null) { connection = HttpConfigurable.getInstance().openHttpConnection(url); } else { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setReadTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT); connection.setConnectTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT); }// www . ja v a2 s . c o m connection.connect(); inputStreams[0] = connection.getInputStream(); } catch (IOException e) { exception[0] = e; } } }); try { downloadThreadFuture.get(5, TimeUnit.SECONDS); } catch (TimeoutException ignored) { } if (!downloadThreadFuture.isDone()) { downloadThreadFuture.cancel(true); throw new ConnectionException(IdeBundle.message("updates.timeout.error")); } if (exception[0] != null) throw exception[0]; return inputStreams[0]; }
From source file:com.newrelic.agent.Deployments.java
static int recordDeployment(CommandLine cmd, AgentConfig config)/* 37: */ throws Exception /* 38: */ {// ww w . java 2s.c om /* 39: 35 */ String appName = config.getApplicationName(); /* 40: 36 */ if (cmd.hasOption("appname")) { /* 41: 37 */ appName = cmd.getOptionValue("appname"); /* 42: */ } /* 43: 39 */ if (appName == null) { /* 44: 40 */ throw new IllegalArgumentException( "A deployment must be associated with an application. Set app_name in newrelic.yml or specify the application name with the -appname switch."); /* 45: */ } /* 46: 43 */ System.out.println("Recording a deployment for application " + appName); /* 47: */ /* 48: 45 */ String uri = "/deployments.xml"; /* 49: 46 */ String payload = getDeploymentPayload(appName, cmd); /* 50: 47 */ String protocol = "http" + (config.isSSL() ? "s" : ""); /* 51: 48 */ URL url = new URL(protocol, config.getApiHost(), config.getApiPort(), uri); /* 52: */ /* 53: 50 */ System.out.println(MessageFormat.format("Opening connection to {0}:{1}", new Object[] { config.getApiHost(), Integer.toString(config.getApiPort()) })); /* 54: */ /* 55: */ /* 56: 53 */ HttpURLConnection conn = (HttpURLConnection) url.openConnection(); /* 57: 54 */ conn.setRequestProperty("x-license-key", config.getLicenseKey()); /* 58: */ /* 59: 56 */ conn.setRequestMethod("POST"); /* 60: 57 */ conn.setConnectTimeout(10000); /* 61: 58 */ conn.setReadTimeout(10000); /* 62: 59 */ conn.setDoOutput(true); /* 63: 60 */ conn.setDoInput(true); /* 64: */ /* 65: 62 */ conn.setRequestProperty("Content-Length", Integer.toString(payload.length())); /* 66: 63 */ conn.setFixedLengthStreamingMode(payload.length()); /* 67: 64 */ conn.getOutputStream().write(payload.getBytes()); /* 68: */ /* 69: 66 */ int responseCode = conn.getResponseCode(); /* 70: 67 */ if (responseCode < 300) /* 71: */ { /* 72: 68 */ System.out.println("Deployment successfully recorded"); /* 73: */ } /* 74: 69 */ else if (responseCode == 401) /* 75: */ { /* 76: 70 */ System.out.println( "Unable to notify New Relic of the deployment because of an authorization error. Check your license key."); /* 77: 71 */ System.out.println("Response message: " + conn.getResponseMessage()); /* 78: */ } /* 79: */ else /* 80: */ { /* 81: 73 */ System.out.println("Unable to notify New Relic of the deployment"); /* 82: 74 */ System.out.println("Response message: " + conn.getResponseMessage()); /* 83: */ } /* 84: 76 */ boolean isError = responseCode >= 300; /* 85: 77 */ if ((isError) || (config.isDebugEnabled())) /* 86: */ { /* 87: 78 */ System.out.println("Response code: " + responseCode); /* 88: 79 */ InputStream inStream = isError ? conn.getErrorStream() : conn.getInputStream(); /* 89: 81 */ if (inStream != null) /* 90: */ { /* 91: 82 */ ByteArrayOutputStream output = new ByteArrayOutputStream(); /* 92: 83 */ Streams.copy(inStream, output); /* 93: */ /* 94: 85 */ PrintStream out = isError ? System.err : System.out; /* 95: */ /* 96: 87 */ out.println(output); /* 97: */ } /* 98: */ } /* 99: 90 */ return responseCode; /* 100: */ }
From source file:com.heraldapp.share.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * /*ww w .j a v a2s .co m*/ * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url * - the resource to open: must be a welformed URL * @param method * - the HTTP method to use ("GET", "POST", etc.) * @param params * - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException * - if the URL format is invalid * @throws IOException * - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } String response = ""; HttpURLConnection conn = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); conn.setReadTimeout(10000); conn.setConnectTimeout(10000); if (!method.equals("GET")) { // use method override params.putString("method", method); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8")); } response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } catch (SocketTimeoutException e) { return response; } return response; }
From source file:ee.ria.xroad.proxy.ProxyMain.java
private static Map<String, DiagnosticsStatus> checkConnectionToTimestampUrl() { Map<String, DiagnosticsStatus> statuses = new HashMap<>(); for (String tspUrl : ServerConf.getTspUrl()) { try {//from ww w. j a v a 2 s. c o m URL url = new URL(tspUrl); log.info("Checking timestamp server status for url {}", url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(DIAGNOSTICS_CONNECTION_TIMEOUT_MS); con.setReadTimeout(DIAGNOSTICS_READ_TIMEOUT_MS); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/timestamp-query"); con.connect(); log.info("Checking timestamp server con {}", con); if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { log.warn("Timestamp check received HTTP error: {} - {}. Might still be ok", con.getResponseCode(), con.getResponseMessage()); statuses.put(tspUrl, new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl)); } else { statuses.put(tspUrl, new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl)); } } catch (Exception e) { log.warn("Timestamp status check failed {}", e); statuses.put(tspUrl, new DiagnosticsStatus(DiagnosticsUtils.getErrorCode(e), LocalTime.now(), tspUrl)); } } return statuses; }
From source file:com.onesignal.OneSignalRestClient.java
private static void makeRequest(String url, String method, JSONObject jsonBody, ResponseHandler responseHandler) { HttpURLConnection con = null; int httpResponse = -1; String json = null;/*from w ww . j av a2s.c o m*/ try { con = (HttpURLConnection) new URL(BASE_URL + url).openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); if (jsonBody != null) con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestMethod(method); if (jsonBody != null) { String strJsonBody = jsonBody.toString(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody); byte[] sendBytes = strJsonBody.getBytes("UTF-8"); con.setFixedLengthStreamingMode(sendBytes.length); OutputStream outputStream = con.getOutputStream(); outputStream.write(sendBytes); } httpResponse = con.getResponseCode(); InputStream inputStream; Scanner scanner; if (httpResponse == HttpURLConnection.HTTP_OK) { inputStream = con.getInputStream(); scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json); if (responseHandler != null) responseHandler.onSuccess(json); } else { inputStream = con.getErrorStream(); if (inputStream == null) inputStream = con.getInputStream(); if (inputStream != null) { scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json); } else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " HTTP Code: " + httpResponse + " No response body!"); if (responseHandler != null) responseHandler.onFailure(httpResponse, json, null); } } catch (Throwable t) { if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException) OneSignal.Log(OneSignal.LOG_LEVEL.INFO, "Could not send last request, device is offline. Throwable: " + t.getClass().getName()); else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t); if (responseHandler != null) responseHandler.onFailure(httpResponse, null, t); } finally { if (con != null) con.disconnect(); } }
From source file:io.webfolder.cdp.ChromiumDownloader.java
public static ChromiumVersion getLatestVersion() { String url = DOWNLOAD_HOST;/*from w ww . j a v a 2 s. c o m*/ if (WINDOWS) { url += "/Win_x64/LAST_CHANGE"; } else if (LINUX) { url += "/Linux_x64/LAST_CHANGE"; } else if (MAC) { url += "/Mac/LAST_CHANGE"; } else { throw new CdpException("Unsupported OS found - " + OS); } try { URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); if (conn.getResponseCode() != 200) { throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage()); } String result = null; try (Scanner s = new Scanner(conn.getInputStream())) { s.useDelimiter("\\A"); result = s.hasNext() ? s.next() : ""; } return new ChromiumVersion(Integer.parseInt(result)); } catch (IOException e) { throw new CdpException(e); } }
From source file:com.magnet.tools.tests.MagnetToolStepDefs.java
@Then("The server at \"([^\"]*)\" is down$") public static void _the_server_at_is_down(String endpointUrl) { try {/*from w w w .j a va2 s . c om*/ HttpURLConnection connection = (HttpURLConnection) new URL(endpointUrl).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setRequestMethod("GET"); connection.getResponseCode(); Assert.fail("the endpoint " + endpointUrl + " should not have been available"); } catch (MalformedURLException e) { throw new AssertionError(e); } catch (IOException e) { // this is what we are hoping for.. } }
From source file:com.bloomreach.bstore.highavailability.utils.SolrInteractionUtils.java
/** * Execute a Http Command with a given read Timeout * * @param timeout/*from ww w . j ava 2s. c o m*/ * @param command * @return {@link java.io.InputStream} of the obtained response * @throws IOException */ public static InputStream executeSolrCommandAndGetInputStreamWithTimeout(int timeout, String command) throws IOException { //logger.info("Command to Execute: " + command); URL obj = new URL(command); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(timeout); //set timeout to 30 seconds con.setReadTimeout(timeout); //set timeout to 30 seconds return con.getInputStream(); }