List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.googlecode.jmxtrans.model.output.StackdriverWriter.java
/** * Post the formatted results to the gateway URL over HTTP * /*from w w w . j a v a 2s .c om*/ * @param gatewayMessage String in the Stackdriver custom metrics JSON format containing the data points */ private void doSend(final String gatewayMessage) { HttpURLConnection urlConnection = null; try { if (proxy == null) { urlConnection = (HttpURLConnection) gatewayUrl.openConnection(); } else { urlConnection = (HttpURLConnection) gatewayUrl.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(timeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey); // Stackdriver's own implementation does not specify char encoding // to use. Let's take the simplest approach and at lest ensure that // if we have problems they can be reproduced in consistant ways. // See https://github.com/Stackdriver/stackdriver-custommetrics-java/blob/master/src/main/java/com/stackdriver/api/custommetrics/CustomMetricsPoster.java#L262 // for details. urlConnection.getOutputStream().write(gatewayMessage.getBytes(ISO_8859_1)); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200 && responseCode != 201) { logger.warn("Failed to send results to Stackdriver server: responseCode=" + responseCode + " message=" + urlConnection.getResponseMessage()); } } catch (Exception e) { logger.warn("Failure to send result to Stackdriver server", e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); in.close(); InputStream err = urlConnection.getErrorStream(); if (err != null) { err.close(); } urlConnection.disconnect(); } catch (IOException e) { logger.warn("Error flushing http connection for one result, continuing"); logger.debug("Stack trace for the http connection, usually a network timeout", e); } } } }
From source file:com.example.android.networkconnect.MainActivity.java
/** * Given a string representation of a URL, sets up a connection and gets * an input stream./* w ww . j a v a 2 s . c om*/ * * @param urlString A string representation of a URL. * @return An InputStream retrieved from a successful HttpURLConnection. * @throws java.io.IOException */ private InputStream downloadUrl(String urlString) throws IOException { // BEGIN_INCLUDE(get_inputstream) URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setRequestProperty("User-Agent", "e-venement-app/"); // Start the query conn.connect(); InputStream stream = conn.getInputStream(); return stream; // END_INCLUDE(get_inputstream) }
From source file:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java
public Envelope wsCall(String location, String username, String password, boolean ignoreCertPath, String xml, String soapAction) throws IOException, SOAPException { URI serviceLocation;//from w w w . j av a 2s . c o m try { serviceLocation = new URI(location); } catch (URISyntaxException e) { throw new IOException("Invalid uri for artifact resolve: " + location); } if (log.isDebugEnabled()) log.debug("serviceLocation..:" + serviceLocation); if (log.isDebugEnabled()) log.debug("SOAP Request: " + xml); HttpURLConnection c = (HttpURLConnection) serviceLocation.toURL().openConnection(); if (c instanceof HttpsURLConnection) { HttpsURLConnection sc = (HttpsURLConnection) c; if (ignoreCertPath) { sc.setSSLSocketFactory(new DummySSLSocketFactory()); sc.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); } } c.setAllowUserInteraction(false); c.setDoInput(true); c.setDoOutput(true); c.setFixedLengthStreamingMode(xml.getBytes("UTF-8").length); c.setRequestMethod("POST"); c.setReadTimeout(20000); c.setConnectTimeout(30000); addContentTypeHeader(xml, c); c.addRequestProperty("SOAPAction", "\"" + (soapAction == null ? "" : soapAction) + "\""); if (username != null && password != null) { c.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes((username + ":" + password).getBytes(), Base64.DONT_BREAK_LINES)); } OutputStream outputStream = c.getOutputStream(); IOUtils.write(xml, outputStream, "UTF-8"); outputStream.flush(); outputStream.close(); if (c.getResponseCode() == 200) { InputStream inputStream = c.getInputStream(); String result = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); if (log.isDebugEnabled()) log.debug("Server SOAP response: " + result); XMLObject res = SAMLUtil.unmarshallElementFromString(result); Envelope envelope = (Envelope) res; if (SAMLUtil.getFirstElement(envelope.getBody(), Fault.class) != null) { log.warn( "Result has soap11:Fault, but server returned 200 OK. Treating as error, please fix the server"); throw new SOAPException(c.getResponseCode(), result); } return envelope; } else { log.debug("Response code: " + c.getResponseCode()); InputStream inputStream = c.getErrorStream(); String result = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); if (log.isDebugEnabled()) log.debug("Server SOAP fault: " + result); throw new SOAPException(c.getResponseCode(), result); } }
From source file:com.sap.wec.adtreco.be.ODataClientService.java
private HttpURLConnection initializeConnection(final String absoluteUri, final String contentType, final String httpMethod) { LOG.info("Initialize connection for URL: " + absoluteUri); HttpURLConnection connection = null; try {// w ww. j a v a 2 s .co m final URL url = new URL(absoluteUri); if (getProxyHost() != null) { final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(getProxyHost(), getProxyPort())); connection = (HttpURLConnection) url.openConnection(proxy); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setRequestProperty(HTTP_HEADER_ACCEPT, contentType); connection.setRequestMethod(httpMethod); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT_RT); } catch (final IOException IOe) { (new Exception("Error initializing connection to CEI: " + absoluteUri, IOe)).printStackTrace(); } if (HTTP_METHOD_POST.equals(httpMethod) || HTTP_METHOD_PUT.equals(httpMethod)) { connection.setDoOutput(true); connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, contentType); } if (this.user != null) { String authorization = "Basic "; authorization += new String(Base64.encodeBase64((this.user + ":" + this.password).getBytes())); connection.setRequestProperty("Authorization", authorization); } LOG.info("End of initialize connection"); return connection; }
From source file:com.athenahealth.api.APIConnection.java
private HttpURLConnection openConnection(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn instanceof HttpsURLConnection) { SSLSocketFactory ssf = getSSLSocketFactory(); if (null != ssf) ((HttpsURLConnection) conn).setSSLSocketFactory(ssf); }//from w w w . jav a 2s . c om conn.setConnectTimeout(getSocketConnectTimeout()); conn.setReadTimeout(getSocketReadTimeout()); return conn; }
From source file:com.example.android.network.sync.basicsyncadapter.SyncAdapter.java
/** * Given a string representation of a URL, sets up a connection and gets an input stream. *//*from w ww. ja va 2 s . co m*/ private SyncResult doFetchAllForURL(Class sClass, SyncResult sResults) throws IOException { try { Method urlForFetchAllMethod = sClass.getDeclaredMethod("urlForFetchAll", null); String urlForFetchAll = (String) urlForFetchAllMethod.invoke(null, null); System.out.println(urlForFetchAll); final URL fetchAllURL = new URL(urlForFetchAll); HttpURLConnection conn = (HttpURLConnection) fetchAllURL.openConnection(); conn.setRequestProperty("X-Parse-Application-Id", "TsEDR12ICJtD59JM92WslVurN0wh5JPuznKvroRc"); conn.setRequestProperty("X-Parse-REST-API-Key", "4LC6oFNCyqLMFHSdPIPsxJoXHY6gTHGMG2kUcbwB"); conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */); conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); Log.i(TAG, "Response from parse.com : " + conn.getResponseMessage()); Log.i(TAG, "Status Code from parse.com : " + conn.getResponseCode()); Class[] cArg = new Class[3]; cArg[0] = Context.class; cArg[1] = InputStream.class; cArg[2] = SyncResult.class; Method handleDataForModel = sClass.getDeclaredMethod("handleInsertWithData", cArg); SyncResult objectsUpdated = (SyncResult) handleDataForModel.invoke(null, this.getContext(), conn.getInputStream(), sResults); return objectsUpdated; } catch (Exception ex) { Log.i(TAG, "exception " + ex.toString()); } return sResults; }
From source file:hudson.remoting.Engine.java
@SuppressWarnings({ "ThrowableInstanceNeverThrown" }) @Override/* w w w .j a v a 2s.co m*/ public void run() { try { boolean first = true; while (true) { if (first) { first = false; } else { if (noReconnect) return; // exit } listener.status("Locating server among " + candidateUrls); Throwable firstError = null; String port = null; for (URL url : candidateUrls) { String s = url.toExternalForm(); if (!s.endsWith("/")) s += '/'; URL salURL = new URL(s + "tcpSlaveAgentListener/"); // find out the TCP port HttpURLConnection con = (HttpURLConnection) salURL.openConnection(); if (con instanceof HttpURLConnection && credentials != null) { String encoding = new String(Base64.encodeBase64(credentials.getBytes())); con.setRequestProperty("Authorization", "Basic " + encoding); } try { try { con.setConnectTimeout(30000); con.setReadTimeout(60000); con.connect(); } catch (IOException x) { if (firstError == null) { firstError = new IOException( "Failed to connect to " + salURL + ": " + x.getMessage()).initCause(x); } continue; } port = con.getHeaderField("X-Hudson-JNLP-Port"); if (con.getResponseCode() != 200) { if (firstError == null) firstError = new Exception(salURL + " is invalid: " + con.getResponseCode() + " " + con.getResponseMessage()); continue; } if (port == null) { if (firstError == null) firstError = new Exception(url + " is not Hudson"); continue; } } finally { con.disconnect(); } // this URL works. From now on, only try this URL hudsonUrl = url; firstError = null; candidateUrls = Collections.singletonList(hudsonUrl); break; } if (firstError != null) { listener.error(firstError); return; } Socket s = connect(port); listener.status("Handshaking"); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); BufferedInputStream in = new BufferedInputStream(s.getInputStream()); dos.writeUTF("Protocol:JNLP2-connect"); Properties props = new Properties(); props.put("Secret-Key", secretKey); props.put("Node-Name", slaveName); if (cookie != null) props.put("Cookie", cookie); ByteArrayOutputStream o = new ByteArrayOutputStream(); props.store(o, null); dos.writeUTF(o.toString("UTF-8")); String greeting = readLine(in); if (greeting.startsWith("Unknown protocol")) { LOGGER.info("The server didn't understand the v2 handshake. Falling back to v1 handshake"); s.close(); s = connect(port); in = new BufferedInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:JNLP-connect"); dos.writeUTF(secretKey); dos.writeUTF(slaveName); greeting = readLine(in); // why, oh why didn't I use DataOutputStream when writing to the network? if (!greeting.equals(GREETING_SUCCESS)) { onConnectionRejected(greeting); continue; } } else { if (greeting.equals(GREETING_SUCCESS)) { Properties responses = readResponseHeaders(in); cookie = responses.getProperty("Cookie"); } else { onConnectionRejected(greeting); continue; } } final Socket socket = s; final Channel channel = new Channel("channel", executor, in, new BufferedOutputStream(s.getOutputStream())); PingThread t = new PingThread(channel) { protected void onDead() { try { if (!channel.isInClosed()) { LOGGER.info("Ping failed. Terminating the socket."); socket.close(); } } catch (IOException e) { LOGGER.log(SEVERE, "Failed to terminate the socket", e); } } }; t.start(); listener.status("Connected"); channel.join(); listener.status("Terminated"); t.interrupt(); // make sure the ping thread is terminated listener.onDisconnect(); if (noReconnect) return; // exit // try to connect back to the server every 10 secs. waitForServerToBack(); } } catch (Throwable e) { listener.error(e); } }
From source file:com.huixueyun.tifenwang.api.net.HttpEngine.java
/** * ?connection// ww w .j a v a 2 s . co m * * @param paramUrl ?? * @return HttpURLConnection */ private HttpURLConnection getConnection(String paramUrl) { HttpURLConnection connection = null; // ?connection try { // ??URL URL url = new URL(SERVER_URL + paramUrl); // ?URL connection = (HttpURLConnection) url.openConnection(); // ? connection.setRequestMethod(REQUEST_MOTHOD); // ??POST?true connection.setDoInput(true); // ??POST? connection.setDoOutput(true); // ? connection.setUseCaches(false); // connection.setReadTimeout(TIME_OUT); connection.setConnectTimeout(TIME_OUT); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Connection", "keep-alive"); connection.setRequestProperty("Response-Type", "json"); connection.setChunkedStreamingMode(0); } catch (IOException e) { e.printStackTrace(); } return connection; }
From source file:com.hmsoft.libcommon.gopro.GoProController.java
private HttpURLConnection getHttpURLConnection(String urlStr) { URL url;/*from w w w.ja v a 2 s. com*/ try { url = new URL(urlStr); } catch (MalformedURLException e) { Log.wtf(TAG, e); return null; } HttpURLConnection urlConnection; try { urlConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Logger.error(TAG, "Can't connect to camera.", e); return null; } if (BuildConfig.DEBUG) Logger.debug(TAG, "Connected to URL: %s", urlStr); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(10000); return urlConnection; }
From source file:org.jetbrains.webdemo.handlers.ServerHandler.java
private void forwardRequestToBackend(HttpServletRequest request, HttpServletResponse response, Map<String, String> postParameters) { final boolean hasoutbody = (request.getMethod().equals("POST")); try {//from w w w. j a va2 s . co m final URL url = new URL("http://" + ApplicationSettings.BACKEND_URL + "/" + (request.getQueryString() != null ? "?" + request.getQueryString() : "")); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); final Enumeration<String> headers = request.getHeaderNames(); while (headers.hasMoreElements()) { final String header = headers.nextElement(); final Enumeration<String> values = request.getHeaders(header); while (values.hasMoreElements()) { final String value = values.nextElement(); conn.addRequestProperty(header, value); } } conn.setConnectTimeout(15000); conn.setReadTimeout(15000); conn.setUseCaches(false); conn.setDoOutput(hasoutbody); if (postParameters != null && !postParameters.isEmpty()) { conn.setRequestMethod("POST"); try (OutputStream requestBody = conn.getOutputStream()) { boolean first = true; for (Map.Entry<String, String> entry : postParameters.entrySet()) { if (entry.getValue() == null) continue; if (first) { first = false; } else { requestBody.write('&'); } requestBody.write(URLEncoder.encode(entry.getKey(), "UTF8").getBytes()); requestBody.write('='); requestBody.write(URLEncoder.encode(entry.getValue(), "UTF8").getBytes()); } } } else { conn.setRequestMethod("GET"); } StringBuilder responseBody = new StringBuilder(); if (conn.getResponseCode() >= 400) { StringBuilder serverMessage = new StringBuilder(); try (InputStream errorStream = conn.getErrorStream()) { if (errorStream != null) { byte[] buffer = new byte[1024]; while (true) { final int read = errorStream.read(buffer); if (read <= 0) break; serverMessage.append(new String(buffer, 0, read)); } } } switch (conn.getResponseCode()) { case HttpServletResponse.SC_NOT_FOUND: responseBody.append("Kotlin compile server not found"); break; case HttpServletResponse.SC_SERVICE_UNAVAILABLE: responseBody.append("Kotlin compile server is temporary overloaded"); break; default: responseBody = serverMessage; break; } } else { try (InputStream inputStream = conn.getInputStream()) { if (inputStream != null) { byte[] buffer = new byte[1024]; while (true) { final int read = inputStream.read(buffer); if (read <= 0) break; responseBody.append(new String(buffer, 0, read)); } } } } writeResponse(request, response, responseBody.toString(), conn.getResponseCode()); } catch (SocketTimeoutException e) { writeResponse(request, response, "Compile server connection timeout", HttpServletResponse.SC_GATEWAY_TIMEOUT); } catch (Exception e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "FORWARD_REQUEST_TO_BACKEND", "", "Can't forward request to Kotlin compile server"); writeResponse(request, response, "Can't send your request to Kotlin compile server", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }