List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.owly.srv.RemoteBasicStatItfImpl.java
public RemoteBasicStat getRemoteStatistic(String nameSrv, String ipSrv, String typeSrv, String typeStat, int clientPort) { URL url = null;/*from ww w .ja v a2s.c o m*/ BufferedReader reader = null; StringBuilder stringBuilder; JSONObject objJSON = new JSONObject(); JSONParser objParser = new JSONParser(); RemoteBasicStat remoteBasicStat = new RemoteBasicStat(); HttpURLConnection connection; // URL ot execute and get a Basic Stadistic. // Url to send to remote server // for example : // http://135.1.128.127:5000/OwlyClnt/Stats_TopCPU String urlToSend = "http://" + ipSrv + ":" + clientPort + "/OwlyClnt/" + typeStat; logger.debug("URL for HTTP request : " + urlToSend); try { url = new URL(urlToSend); connection = (HttpURLConnection) url.openConnection(); // just want to do an HTTP GET here connection.setRequestMethod("GET"); // uncomment this if you want to write output to this url // connection.setDoOutput(true); // give it 15 seconds to respond connection.setReadTimeout(3 * 1000); connection.connect(); // read the output from the server reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } logger.debug("Response received : " + stringBuilder.toString()); // Get the response and save into a JSON object, and parse the // JSON object objJSON = (JSONObject) objParser.parse(stringBuilder.toString()); logger.debug("JSON received : " + objJSON.toString()); // Add all info received in a new object of satistics remoteBasicStat.setRmtSeverfromJSONObject(objJSON); // Add more details for the stadistics. remoteBasicStat.setIpServer(ipSrv); logger.debug("IP of server : " + remoteBasicStat.getIpServer()); remoteBasicStat.setNameServer(nameSrv); logger.debug("Name of Server : " + remoteBasicStat.getNameServer()); remoteBasicStat.setTypeServer(typeSrv); logger.debug("Type of Server : " + remoteBasicStat.getTypeServer()); } catch (MalformedURLException e) { logger.error("MalformedURLException : " + e.getMessage()); logger.error("Exception ::", e); } catch (IOException e) { logger.error("IOException : " + e.toString()); logger.error("Exception ::", e); } catch (ParseException e) { logger.error("ParseException : " + e.toString()); logger.error("Exception ::", e); } return remoteBasicStat; }
From source file:RhodesService.java
public static boolean pingHost(String host) { HttpURLConnection conn = null; boolean hostExists = false; try {//from w ww. ja va 2s .c o m URL url = new URL(host); HttpURLConnection.setFollowRedirects(false); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.setAllowUserInteraction(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); hostExists = (conn.getContentLength() > 0); if (hostExists) Logger.I(TAG, "PING network SUCCEEDED."); else Logger.E(TAG, "PING network FAILED."); } catch (Exception e) { Logger.E(TAG, e); } finally { if (conn != null) { try { conn.disconnect(); } catch (Exception e) { Logger.E(TAG, e); } } } return hostExists; }
From source file:uk.co.jassoft.network.Network.java
public InputStream read(String httpUrl, String method, boolean cache) throws IOException { HttpURLConnection conn = null; try {/*from w ww. j a v a 2 s . c om*/ URL base, next; String location; while (true) { // inputing the keywords to google search engine URL url = new URL(httpUrl); // if(cache) { // //Proxy instance, proxy ip = 10.0.0.1 with port 8080 // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("cache", 3128)); // // makking connection to the internet // conn = (HttpURLConnection) url.openConnection(proxy); // } // else { conn = (HttpURLConnection) url.openConnection(); // } conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); conn.setRequestMethod(method); conn.setRequestProperty("User-Agent", "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)"); conn.setRequestProperty("Accept-Encoding", "gzip"); switch (conn.getResponseCode()) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: location = conn.getHeaderField("Location"); base = new URL(httpUrl); next = new URL(base, location); // Deal with relative URLs httpUrl = next.toExternalForm(); continue; } break; } if (!conn.getContentType().startsWith("text/") || conn.getContentType().equals("text/xml")) { throw new IOException(String.format("Content of story is not Text. Returned content type is [%s]", conn.getContentType())); } if ("gzip".equals(conn.getContentEncoding())) { return new GZIPInputStream(conn.getInputStream()); } // getting the input stream of page html into bufferedreader return conn.getInputStream(); } catch (Exception exception) { throw new IOException(exception); } finally { if (conn != null && conn.getErrorStream() != null) { conn.getErrorStream().close(); } } }
From source file:net.caseif.flint.steel.lib.net.gravitydevelopment.updater.Updater.java
private URL followRedirects(String location) throws IOException { URL resourceUrl, base, next;//from w w w. java2 s . c o m HttpURLConnection conn; String redLoc; while (true) { resourceUrl = new URL(location); conn = (HttpURLConnection) resourceUrl.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(15000); conn.setInstanceFollowRedirects(false); conn.setRequestProperty("User-Agent", "Mozilla/5.0..."); switch (conn.getResponseCode()) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: redLoc = conn.getHeaderField("Location"); base = new URL(location); next = new URL(base, redLoc); // Deal with relative URLs location = next.toExternalForm(); continue; } break; } return conn.getURL(); }
From source file:info.aamulumi.sharedshopping.network.RequestSender.java
/** * Send HTTP Request with params (x-url-encoded) * * @param requestURL - URL of the request * @param method - HTTP method (GET, POST, PUT, DELETE, ...) * @param urlParameters - parameters send in URL * @param bodyParameters - parameters send in body (encoded) * @return JSONObject returned by the server *//* w w w .ja v a2 s .c o m*/ public JSONObject makeHttpRequest(String requestURL, String method, HashMap<String, String> urlParameters, HashMap<String, String> bodyParameters) { HttpURLConnection connection = null; URL url; JSONObject jObj = null; try { // Check if we must add parameters in URL if (urlParameters != null) { String stringUrlParams = getFormattedParameters(urlParameters); url = new URL(requestURL + "?" + stringUrlParams); } else url = new URL(requestURL); // Create connection connection = (HttpURLConnection) url.openConnection(); // Add cookies to request if (mCookieManager.getCookieStore().getCookies().size() > 0) connection.setRequestProperty("Cookie", TextUtils.join(";", mCookieManager.getCookieStore().getCookies())); // Set request parameters connection.setReadTimeout(5000); connection.setConnectTimeout(5000); connection.setRequestMethod(method); connection.setDoInput(true); // Check if we must add parameters in body if (bodyParameters != null) { // Create a string with parameters String stringBodyParameters = getFormattedParameters(bodyParameters); // Set output request parameters connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(stringBodyParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "fr-FR"); // Send body's request OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(stringBodyParameters); writer.flush(); writer.close(); os.close(); } // Get response code int responseCode = connection.getResponseCode(); // If response is 200 (OK) if (responseCode == HttpsURLConnection.HTTP_OK) { // Keep new cookies in the manager List<String> cookiesHeader = connection.getHeaderFields().get(COOKIES_HEADER); if (cookiesHeader != null) { for (String cookie : cookiesHeader) mCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0)); } // Read the response String line; BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } // Parse the response to a JSON Object try { jObj = new JSONObject(sb.toString()); } catch (JSONException e) { Log.d("JSON Parser", "Error parsing data " + e.toString()); Log.d("JSON Parser", "Setting value of jObj to null"); jObj = null; } } else { Log.w("HttpUrlConnection", "Error : server sent code : " + responseCode); } } catch (MalformedURLException e) { Log.e("Network", "Error in URL"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // Close connection if (connection != null) connection.disconnect(); } return jObj; }
From source file:com.gtx.cooliris.imagecache.ImageFetcher.java
/** * Download a bitmap from a URL and write the content to an output stream. * * @param urlString The URL to fetch/*from w w w.j a va 2 s .c o m*/ * @return true if successful, false otherwise */ public boolean downloadUrlToStream(String urlString, OutputStream outputStream) { disableConnectionReuseIfNecessary(); HttpURLConnection urlConnection = null; BufferedOutputStream out = null; BufferedInputStream in = null; try { final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); // Add by liulin // Set connecting timeout and socket timeout. urlConnection.setConnectTimeout(CONNECT_TIMEOUT); urlConnection.setReadTimeout(SOCKET_TIMEOUT); in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE); out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE); int b; while ((b = in.read()) != -1) { out.write(b); } return true; } catch (final IOException e) { LogUtil.e(TAG, "Error in downloadBitmap - " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (final IOException e) { } } return false; }
From source file:com.frostwire.gui.updates.UpdateMessageReader.java
public void readUpdateFile() { HttpURLConnection connection = null; InputSource src = null;/*from w w w. ja va 2 s .c o m*/ try { String userAgent = "FrostWire/" + OSUtils.getOS() + "-" + OSUtils.getArchitecture() + "/" + FrostWireUtils.getFrostWireVersion(); connection = (HttpURLConnection) (new URL(getUpdateURL())).openConnection(); String url = getUpdateURL(); System.out.println("Reading update file from " + url); connection.setRequestProperty("User-Agent", userAgent); connection.setRequestProperty("Connection", "close"); connection.setReadTimeout(10000); // 10 secs timeout if (connection.getResponseCode() >= 400) { // invalid URL for sure connection.disconnect(); return; } src = new InputSource(connection.getInputStream()); XMLReader rdr = XMLReaderFactory .createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser"); rdr.setContentHandler(this); rdr.parse(src); connection.getInputStream().close(); connection.disconnect(); } catch (java.net.SocketTimeoutException e3) { System.out.println("UpdateMessageReadre.readUpdateFile() Socket Timeout Exeception " + e3.toString()); } catch (IOException e) { System.out.println("UpdateMessageReader.readUpdateFile() IO exception " + e.toString()); } catch (SAXException e2) { System.out.println("UpdateMessageReader.readUpdateFile() SAX exception " + e2.toString()); } }
From source file:com.bazaarvoice.seo.sdk.BVUIContentServiceProvider.java
private String loadContentFromHttp(URI path) { int connectionTimeout = Integer .parseInt(_bvConfiguration.getProperty(BVClientConfig.CONNECT_TIMEOUT.getPropertyName())); int socketTimeout = Integer .parseInt(_bvConfiguration.getProperty(BVClientConfig.SOCKET_TIMEOUT.getPropertyName())); String proxyHost = _bvConfiguration.getProperty(BVClientConfig.PROXY_HOST.getPropertyName()); String charsetConfig = _bvConfiguration.getProperty(BVClientConfig.CHARSET.getPropertyName()); Charset charset = null;/*w ww .j a v a 2 s . co m*/ try { charset = charsetConfig == null ? Charset.defaultCharset() : Charset.forName(charsetConfig); } catch (Exception e) { _logger.error(BVMessageUtil.getMessage("ERR0024")); charset = Charset.defaultCharset(); } String content = null; try { HttpURLConnection httpUrlConnection = null; URL url = path.toURL(); if (!StringUtils.isBlank(proxyHost) && !"none".equalsIgnoreCase(proxyHost)) { int proxyPort = Integer .parseInt(_bvConfiguration.getProperty(BVClientConfig.PROXY_PORT.getPropertyName())); SocketAddress socketAddress = new InetSocketAddress(proxyHost, proxyPort); Proxy proxy = new Proxy(Type.HTTP, socketAddress); httpUrlConnection = (HttpURLConnection) url.openConnection(proxy); } else { httpUrlConnection = (HttpURLConnection) url.openConnection(); } httpUrlConnection.setConnectTimeout(connectionTimeout); httpUrlConnection.setReadTimeout(socketTimeout); InputStream is = httpUrlConnection.getInputStream(); byte[] byteArray = IOUtils.toByteArray(is); is.close(); if (byteArray == null) { throw new BVSdkException("ERR0025"); } content = new String(byteArray, charset.name()); } catch (MalformedURLException e) { // e.printStackTrace(); } catch (IOException e) { // e.printStackTrace(); if (e instanceof SocketTimeoutException) { throw new BVSdkException(e.getMessage()); } else { throw new BVSdkException("ERR0012"); } } catch (BVSdkException bve) { throw bve; } boolean isValidContent = BVUtilty.validateBVContent(content); if (!isValidContent) { throw new BVSdkException("ERR0025"); } return content; }
From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java
private InputStream getInputStreamForImageURL(String urlLocation, String requestMethod) throws Exception { URL url = new URL(urlLocation); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(requestMethod); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16"); connection.setRequestProperty("Accept", "text/plain,text/html,application/xhtml+xml,application/xml"); connection.setRequestProperty("charset", "UTF-8"); connection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout())); connection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout())); applyAuth(connection);// www . ja v a 2 s . c om connection.connect(); return connection.getInputStream(); }
From source file:eu.operando.operandoapp.database.DatabaseHelper.java
public void sendSettingsToServer(final String imei) { new Thread(new Runnable() { @Override//from w w w. j a va 2s . co m public void run() { String xml_settings = exportAllPermissionsPerDomain(); if (xml_settings != null) { try { String urlParameters = "userxml=" + xml_settings + "&userID=" + Base64.encode(DigestUtils.sha1(imei), Base64.DEFAULT); byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); URL url = new URL(serverUrl + "/prefs"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) { wr.write(postData); } int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { //Do something on HTTP_OK ????? } else { throw new Exception(); } Log.d("SENT", Integer.toString(responseCode)); } catch (Exception e) { //create a file as database to resend later Writer writer = null; try { File file = new File(MainContext.INSTANCE.getContext().getFilesDir(), "resend.inf"); if (!file.exists()) { writer = new BufferedWriter(new FileWriter(file)); writer.write("1"); //currently putting 1 for "true" to resend } } catch (Exception ex) { ex.getMessage(); } finally { try { writer.close(); } catch (Exception ex) { ex.getMessage(); } } } } } }).start(); }