List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:edu.usf.cutr.opentripplanner.android.pois.GooglePlaces.java
public JSONObject requestPlaces(String paramLocation, String paramRadius, String paramName) { StringBuilder builder = new StringBuilder(); String encodedParamLocation = ""; String encodedParamRadius = ""; String encodedParamName;//from w w w .j av a 2s. c om try { if ((paramLocation != null) && (paramRadius != null)) { encodedParamLocation = URLEncoder.encode(paramLocation, OTPApp.URL_ENCODING); encodedParamRadius = URLEncoder.encode(paramRadius, OTPApp.URL_ENCODING); } encodedParamName = URLEncoder.encode(paramName, OTPApp.URL_ENCODING); } catch (UnsupportedEncodingException e1) { Log.e(OTPApp.TAG, "Error encoding Google Places request"); e1.printStackTrace(); return null; } if ((paramLocation != null) && (paramRadius != null)) { request += "location=" + encodedParamLocation; request += "&radius=" + encodedParamRadius; request += "&query=" + encodedParamName; } else { request += "query=" + encodedParamName; } request += "&sensor=false"; request += "&key=" + getApiKey(); Log.d(OTPApp.TAG, request); HttpURLConnection urlConnection = null; try { URL url = new URL(request); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT); urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT); urlConnection.connect(); int status = urlConnection.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(OTPApp.TAG, "Error obtaining Google Places response, status code: \" + status"); } } catch (IOException e) { Log.e(OTPApp.TAG, "Error obtaining Google Places response" + e.toString()); e.printStackTrace(); return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } Log.d(OTPApp.TAG, builder.toString()); JSONObject json = null; try { json = new JSONObject(builder.toString()); } catch (JSONException e) { Log.e(OTPApp.TAG, "Error parsing Google Places data " + e.toString()); } return json; }
From source file:com.exzogeni.dk.http.HttpTask.java
private void onPrepareConnectionInternal(HttpURLConnection cn) throws Exception { final URI uri = cn.getURL().toURI(); cn.setRequestMethod(getMethodName()); cn.setConnectTimeout(mTimeoutMs); cn.setReadTimeout(mTimeoutMs);//from w ww. ja v a 2 s . c o m final CookieManager cm = mHttpManager.getCookieManager(); final Map<String, List<String>> cookies = cm.get(uri, new HashMap<String, List<String>>()); for (final Map.Entry<String, List<String>> cookie : cookies.entrySet()) { for (final String value : cookie.getValue()) { cn.addRequestProperty(cookie.getKey(), value); } } for (final Map.Entry<String, List<String>> header : mHeaders.entrySet()) { for (final String value : header.getValue()) { cn.addRequestProperty(header.getKey(), value); } } onPrepareConnection(cn); }
From source file:com.adguard.commons.web.UrlUtils.java
/** * Downloads content from the specified url using specified proxy (or do not using it) and timeouts. * Returns null if there's an error.// w w w. ja va 2 s .c o m * * @param url url * @param proxy proxy to use * @param readTimeout read timeout * @param socketTimeout connection timeout * @return Downloaded string */ public static String downloadString(URL url, Proxy proxy, int readTimeout, int socketTimeout, String encoding) { HttpURLConnection connection = null; InputStream inputStream = null; try { connection = (HttpURLConnection) (proxy == null ? url.openConnection() : url.openConnection(proxy)); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36"); connection.setReadTimeout(readTimeout); connection.setConnectTimeout(socketTimeout); connection.connect(); if (connection.getResponseCode() >= 400) { throw new IOException("Response status is " + connection.getResponseCode()); } if (connection.getResponseCode() >= 301) { String location = connection.getHeaderField("Location"); // HttpURLConnection does not follow redirects from HTTP to HTTPS // So we handle it manually return downloadString(new URL(location), proxy, readTimeout, socketTimeout, encoding); } if (connection.getResponseCode() == 204) { return StringUtils.EMPTY; } inputStream = connection.getInputStream(); return IOUtils.toString(inputStream, encoding); } catch (IOException ex) { if (LOG.isDebugEnabled()) { LOG.warn("Error downloading string from {}:\r\n", url, ex); } else { LOG.warn("Cannot download string from {}: {}", url, ex.getMessage()); } // Ignoring exception return null; } finally { IOUtils.closeQuietly(inputStream); if (connection != null) { connection.disconnect(); } } }
From source file:br.gov.jfrj.siga.base.SigaHTTP.java
public String getNaWeb(String URL, HashMap<String, String> header, Integer timeout, String payload) throws AplicacaoException { try {/*from www . ja va 2 s.c o m*/ HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection(); if (timeout != null) { conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); } //conn.setInstanceFollowRedirects(true); if (header != null) { for (String s : header.keySet()) { conn.setRequestProperty(s, header.get(s)); } } System.setProperty("http.keepAlive", "false"); if (payload != null) { byte ab[] = payload.getBytes("UTF-8"); conn.setRequestMethod("POST"); // Send post request conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(ab); os.flush(); os.close(); } //StringWriter writer = new StringWriter(); //IOUtils.copy(conn.getInputStream(), writer, "UTF-8"); //return writer.toString(); return IOUtils.toString(conn.getInputStream(), "UTF-8"); } catch (IOException ioe) { throw new AplicacaoException("No foi possvel abrir conexo", 1, ioe); } }
From source file:fr.cph.chicago.connection.CtaConnect.java
/** * Connect url/*w w w.j a v a2s .c o m*/ * * @param address the address * @return the answer * @throws ConnectException */ @NonNull private InputStream connectUrl(@NonNull final String address) throws ConnectException { final HttpURLConnection urlConnection; final InputStream inputStream; try { Log.v(TAG, "Address: " + address); final URL url = new URL(address); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); inputStream = new BufferedInputStream(urlConnection.getInputStream()); } catch (final IOException e) { Log.e(TAG, e.getMessage(), e); throw new ConnectException(ConnectException.ERROR, e); } return inputStream; }
From source file:info.smartkit.hairy_batman.query.SogouSearchQuery.java
public String getJsonContent(String urlStr) { try {// ?HttpURLConnection URL url = new URL(urlStr); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); // //ww w . j ava 2 s.co m httpConn.setConnectTimeout(3000); httpConn.setDoInput(true); httpConn.setRequestMethod("GET"); // ?? int respCode = httpConn.getResponseCode(); if (respCode == 200) { String a = ConvertStream2Json(httpConn.getInputStream()); return a.substring(a.indexOf("(") + 1, a.lastIndexOf(")")); } } catch (MalformedURLException e) { LOG.error(e.toString()); } catch (IOException e) { LOG.error(e.toString()); } return ""; }
From source file:ee.ria.xroad.proxy.clientproxy.WsdlRequestProcessor.java
HttpURLConnection createConnection(SoapMessageImpl message) throws Exception { URL url = new URL("http://127.0.0.1:" + SystemProperties.getClientProxyHttpPort()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true);/* w w w . j a v a 2 s . com*/ con.setDoOutput(true); // Use the same timeouts as client proxy to server proxy connections. con.setConnectTimeout(SystemProperties.getClientProxyTimeout()); con.setReadTimeout(SystemProperties.getClientProxyHttpClientTimeout()); con.setRequestMethod("POST"); con.setRequestProperty(HttpHeaders.CONTENT_TYPE, MimeUtils.contentTypeWithCharset(MimeTypes.TEXT_XML, StandardCharsets.UTF_8.name())); IOUtils.write(message.getBytes(), con.getOutputStream()); if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException( "Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage()); } return con; }
From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyServer.java
private String query(String request) throws QueryException, HttpError { InetAddress ips[];// w w w . j a v a 2 s . c o m try { ips = InetAddress.getAllByName(mHost); } catch (UnknownHostException e) { throw new QueryException(e.toString()); } for (int i = 0; i < ips.length; ++i) { try { String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request; Log.d(Constants.TAG, "hkp keyserver query: " + url); URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(25000); conn.connect(); int response = conn.getResponseCode(); if (response >= 200 && response < 300) { return readAll(conn.getInputStream(), conn.getContentEncoding()); } else { String data = readAll(conn.getErrorStream(), conn.getContentEncoding()); throw new HttpError(response, data); } } catch (MalformedURLException e) { // nothing to do, try next IP } catch (IOException e) { // nothing to do, try next IP } } throw new QueryException("querying server(s) for '" + mHost + "' failed"); }
From source file:com.adguard.commons.web.UrlUtils.java
/** * Sends a POST request/*from w ww .ja va 2 s . c om*/ * * @param url URL * @param postData Post request body * @param encoding Post request body encoding * @param contentType Body content type * @param compress If true - compress bod * @param readTimeout Read timeout * @param socketTimeout Socket timeout * @return Response */ public static String postRequest(URL url, String postData, String encoding, String contentType, boolean compress, int readTimeout, int socketTimeout) { HttpURLConnection connection = null; OutputStream outputStream = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); if (contentType != null) { connection.setRequestProperty("Content-Type", contentType); } if (compress) { connection.setRequestProperty("Content-Encoding", "gzip"); } connection.setConnectTimeout(socketTimeout); connection.setReadTimeout(readTimeout); connection.setDoOutput(true); connection.connect(); if (postData != null) { outputStream = connection.getOutputStream(); if (compress) { outputStream = new GZIPOutputStream(outputStream); } if (encoding != null) { IOUtils.write(postData, outputStream, encoding); } else { IOUtils.write(postData, outputStream); } if (compress) { ((GZIPOutputStream) outputStream).finish(); } else { outputStream.flush(); } } return IOUtils.toString(connection.getInputStream(), encoding); } catch (Exception ex) { LOG.error("Error posting request to {}, post data length={}\r\n", url, StringUtils.length(postData), ex); // Ignoring exception return null; } finally { IOUtils.closeQuietly(outputStream); if (connection != null) { connection.disconnect(); } } }
From source file:com.vimc.ahttp.HurlWorker.java
/** * Opens an {@link HttpURLConnection} with parameters. * //from ww w . j av a2 s . c o m * @param url * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); connection.setConnectTimeout(request.connectTimeout); connection.setReadTimeout(request.soTimeout); connection.setUseCaches(false); connection.setDoInput(true); // connection.setRequestProperty("Connection", "close"); if ("https".equals(url.getProtocol())) { if (mSslSocketFactory != null) { ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } else { setDefaultSSLSocketFactory(); } } return connection; }