List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:Main.java
public static String getHtml(String getUrl, int outtime, String charsetName) { String html = ""; URL url;/*from w w w .j ava 2 s. c om*/ try { url = new URL(getUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1; CIBA)"); // connection.setRequestProperty("Connection", "Keep-Alive"); // connection.setRequestProperty("Cache-Control", "no-cache"); connection.setConnectTimeout(outtime); connection.connect(); InputStream inStrm = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, charsetName)); String temp = ""; while ((temp = br.readLine()) != null) { html = html + (temp + '\n'); } try { br.close(); } catch (Exception e) { // TODO: handle exception } try { connection.disconnect(); } catch (Exception e) { // TODO: handle exception } } catch (Exception e) { e.printStackTrace(); } return html; }
From source file:com.newrelic.agent.Deployments.java
static int recordDeployment(CommandLine cmd, AgentConfig config)/* 37: */ throws Exception /* 38: */ {// w w w .jav a2s.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:brainleg.app.util.AppWeb.java
/** * Copied from ITNProxy//from w w w .java 2 s .c o m */ private static HttpURLConnection doPost(String url, byte[] bytes) throws IOException { HttpURLConnection connection = (HttpURLConnection) HttpConfigurable.getInstance().openConnection(url); connection.setReadTimeout(60 * 1000); connection.setConnectTimeout(10 * 1000); connection.setRequestMethod(HTTP_POST); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty(HTTP_CONTENT_TYPE, String.format("%s; charset=%s", HTTP_WWW_FORM, ENCODING)); connection.setRequestProperty(HTTP_CONTENT_LENGTH, Integer.toString(bytes.length)); OutputStream out = new BufferedOutputStream(connection.getOutputStream()); try { out.write(bytes); out.flush(); } finally { out.close(); } return connection; }
From source file:com.vaguehope.onosendai.util.HttpHelper.java
private static <R> R fetchWithFollowRedirects(final Method method, final URL url, final HttpStreamHandler<R> streamHandler, final int redirectCount) throws IOException, URISyntaxException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try {// w w w . j a va2s .c o m connection.setRequestMethod(method.toString()); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS)); connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS)); connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser. //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong. connection.connect(); InputStream is = null; try { final int responseCode = connection.getResponseCode(); // For some reason some devices do not follow redirects. :( if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers. Its HTTP spec. if (redirectCount >= MAX_REDIRECTS) throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS); final String locationHeader = connection.getHeaderField("Location"); if (locationHeader == null) throw new HttpResponseException(responseCode, "Location header missing. Headers present: " + connection.getHeaderFields() + "."); connection.disconnect(); final URL locationUrl; if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) { locationUrl = new URL(locationHeader); } else { locationUrl = url.toURI().resolve(locationHeader).toURL(); } return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1); } if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers. Its HTTP spec. throw new NotOkResponseException(responseCode, connection, url); } is = connection.getInputStream(); final int contentLength = connection.getContentLength(); if (contentLength < 1) LOG.w("Content-Length=%s for %s.", contentLength, url); return streamHandler.handleStream(connection, is, contentLength); } finally { IoHelper.closeQuietly(is); } } finally { connection.disconnect(); } }
From source file:com.dmsl.anyplace.utils.NetworkUtils.java
public static InputStream downloadHttp(String urlS) throws URISyntaxException, IOException { InputStream is = null;/*www . j a v a 2s .c o m*/ URL url = new URL(encodeURL(urlS)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); if (response == 200) { is = conn.getInputStream(); } return is; }
From source file:com.bloomreach.bstore.highavailability.utils.SolrInteractionUtils.java
/** * Execute a Http Command with a given read Timeout * * @param timeout/*from www . j a v a 2 s .co 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(); }
From source file:com.intuit.tank.harness.AmazonUtil.java
/** * @param string//from ww w. jav a 2 s . c o m * @return * @throws IOException */ private static InputStream getInputStream(String url) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(3000); return con.getInputStream(); }
From source file:com.avinashbehera.sabera.network.HttpClient.java
public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) { URL sendUrl;//from w ww.j a va2 s .com try { sendUrl = new URL(url); } catch (MalformedURLException e) { Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL"); return null; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) sendUrl.openConnection(); conn.setReadTimeout(15000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setChunkedStreamingMode(1024); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + ""); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); //writer.write(getPostDataStringfromJsonObject(jsonObjSend)); Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString()); //writer.write(jsonObjSend.toString()); writer.write(String.valueOf(jsonObjSend)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); Log.d(TAG, "responseCode = " + responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { Log.d(TAG, "responseCode = HTTP OK"); InputStream instream = conn.getInputStream(); String resultString = convertStreamToString(instream); instream.close(); Log.d(TAG, "resultString = " + resultString); //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]" // Transform the String into a JSONObject JSONParser parser = new JSONParser(); JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); return jsonObjRecv; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return null; }
From source file:com.gson.util.HttpKit.java
/** * ?http?/*from w w w . j ava 2 s. c o m*/ * @param url * @param method * @param headers * @return * @throws IOException */ private static HttpURLConnection initHttp(String url, String method, Map<String, String> headers) throws IOException { URL _url = new URL(url); HttpURLConnection http = (HttpURLConnection) _url.openConnection(); // http.setConnectTimeout(25000); // ? --?? http.setReadTimeout(25000); http.setRequestMethod(method); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (null != headers && !headers.isEmpty()) { for (Entry<String, String> entry : headers.entrySet()) { http.setRequestProperty(entry.getKey(), entry.getValue()); } } http.setDoOutput(true); http.setDoInput(true); http.connect(); return http; }
From source file:a122016.rr.com.alertme.QueryUtilsPoliceStation.java
/** * Make an HTTP request to the given URL and return a String as the response. *//*from w w w . j a v a2 s. co m*/ private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the PoliceStations JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { // Closing the input stream could throw an IOException, which is why // the makeHttpRequest(URL url) method signature specifies than an IOException // could be thrown. inputStream.close(); } } return jsonResponse; }