Java Code Examples for java.net.HttpURLConnection#setReadTimeout()
The following examples show how to use
java.net.HttpURLConnection#setReadTimeout() .
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: inception File: LappsGridRecommenderConformityTest.java License: Apache License 2.0 | 6 votes |
public static boolean isReachable(String aUrl) { try { URL url = new URL(aUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(2500); con.setReadTimeout(2500); con.setRequestProperty("Content-Type", "application/sparql-query"); int status = con.getResponseCode(); if (status == HTTP_MOVED_TEMP || status == HTTP_MOVED_PERM) { String location = con.getHeaderField("Location"); return isReachable(location); } return true; } catch (Exception e) { return false; } }
Example 2
Source Project: jease File: Urls.java License: GNU General Public License v3.0 | 6 votes |
/** * Returns true if given url can be connected via HTTP within given timeout * (specified in seconds). Otherwise the url might be broken. */ public static boolean isConnectable(String url, int timeout) { try { URLConnection connection = new URL(url).openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setConnectTimeout(timeout * 1000); httpConnection.setReadTimeout(timeout * 1000); httpConnection.connect(); int response = httpConnection.getResponseCode(); httpConnection.disconnect(); return response == HttpURLConnection.HTTP_OK; } } catch (Exception e) { return false; } return false; }
Example 3
Source Project: micro-integrator File: DS1111UserRoleExtensionTestCase.java License: Apache License 2.0 | 6 votes |
/** * This method will return the http response for the request * * @param endpoint service endpoint * @return HttpResponse * @throws Exception */ private HttpResponse getHttpResponse(String endpoint) throws Exception { if (endpoint.startsWith("http://")) { URL url = new URL(endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setRequestProperty("charset", "UTF-8"); conn.setReadTimeout(10000); conn.connect(); // Get the response StringBuilder sb = new StringBuilder(); try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } return new HttpResponse(sb.toString(), conn.getResponseCode()); } return null; }
Example 4
Source Project: openjdk-jdk8u File: B6401598.java License: GNU General Public License v2.0 | 6 votes |
static HttpURLConnection getHttpURLConnection(URL url, int timeout) throws IOException { HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(40000); httpURLConnection.setReadTimeout(timeout); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setAllowUserInteraction(false); httpURLConnection.setRequestMethod("POST"); // HttpURLConnection httpURLConnection = new MyHttpURLConnection(url); return httpURLConnection; }
Example 5
Source Project: okta-sdk-appauth-android File: ConnectionBuilderForTest.java License: Apache License 2.0 | 6 votes |
@NonNull @Override public HttpURLConnection openConnection(@NonNull Uri uri) throws IOException { Preconditions.checkNotNull(uri, "url must not be null"); Preconditions.checkArgument(HTTP.equals(uri.getScheme()) || HTTPS.equals(uri.getScheme()), "scheme or uri must be http or https"); HttpURLConnection conn = (HttpURLConnection) new URL(uri.toString()).openConnection(); conn.setConnectTimeout(CONNECTION_TIMEOUT_MS); conn.setReadTimeout(READ_TIMEOUT_MS); conn.setInstanceFollowRedirects(false); if (conn instanceof HttpsURLConnection && TRUSTING_CONTEXT != null) { HttpsURLConnection httpsConn = (HttpsURLConnection) conn; httpsConn.setSSLSocketFactory(TRUSTING_CONTEXT.getSocketFactory()); httpsConn.setHostnameVerifier(ANY_HOSTNAME_VERIFIER); } return conn; }
Example 6
Source Project: AndroidWallet File: StringUtils.java License: GNU General Public License v3.0 | 6 votes |
public static String getHtml(String path) throws Exception { // 通过网络地址创建URL对象 URL url = new URL(path); // 根据URL // 打开连接,URL.openConnection函数会根据URL的类型,返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设定URL的请求类别,有POST、GET 两类 conn.setRequestMethod("GET"); //设置从主机读取数据超时(单位:毫秒) conn.setConnectTimeout(5000); //设置连接主机超时(单位:毫秒) conn.setReadTimeout(5000); // 通过打开的连接读取的输入流,获取html数据 InputStream inStream = conn.getInputStream(); // 得到html的二进制数据 byte[] data = readInputStream(inStream); // 是用指定的字符集解码指定的字节数组构造一个新的字符串 String html = new String(data, "utf-8"); return html; }
Example 7
Source Project: FeedListViewDemo File: HurlStack.java License: MIT License | 6 votes |
/** * Opens an {@link HttpURLConnection} with parameters. * @param url * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }
Example 8
Source Project: openjdk-8 File: B6401598.java License: GNU General Public License v2.0 | 6 votes |
static HttpURLConnection getHttpURLConnection(URL url, int timeout) throws IOException { HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(40000); httpURLConnection.setReadTimeout(timeout); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setAllowUserInteraction(false); httpURLConnection.setRequestMethod("POST"); // HttpURLConnection httpURLConnection = new MyHttpURLConnection(url); return httpURLConnection; }
Example 9
Source Project: spring-ws File: HttpUrlConnectionMessageSenderTimeout.java License: MIT License | 6 votes |
@Override protected void prepareConnection(HttpURLConnection connection) throws IOException { connection.setRequestMethod(HttpTransportConstants.METHOD_POST); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); if (isAcceptGzipEncoding()) { connection.setRequestProperty( HttpTransportConstants.HEADER_ACCEPT_ENCODING, HttpTransportConstants.CONTENT_ENCODING_GZIP); } // timeout for creating a connection connection.setConnectTimeout(timeout); // when you have a connection, timeout the read blocks for connection.setReadTimeout(timeout); }
Example 10
Source Project: ontology-java-sdk File: http.java License: GNU Lesser General Public License v3.0 | 5 votes |
private static String get(String url ,boolean https) throws Exception { URL u = new URL(url); HttpURLConnection http = (HttpURLConnection) u.openConnection(); http.setConnectTimeout(20000); http.setReadTimeout(20000); http.setRequestMethod("GET"); http.setRequestProperty("Content-Type","application/json"); if(https) { SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, new TrustManager[]{new X509()}, new SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); ((HttpsURLConnection)http).setSSLSocketFactory(ssf); } http.setDoOutput(true); http.setDoInput(true); http.connect(); StringBuilder sb = new StringBuilder(); try (InputStream is = http.getInputStream()) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, DEFAULT_CHARSET))) { String str = null; while((str = reader.readLine()) != null) { sb.append(str); str = null; } } } if (http != null) { http.disconnect(); } return sb.toString(); }
Example 11
Source Project: airsonic File: InternetRadioService.java License: GNU General Public License v3.0 | 5 votes |
/** * Start a new connection to a remote URL. * * @param url the remote URL * @return an open connection */ protected HttpURLConnection connectToURL(URL url) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setAllowUserInteraction(false); urlConnection.setConnectTimeout(10000); urlConnection.setDoInput(true); urlConnection.setDoOutput(false); urlConnection.setReadTimeout(60000); urlConnection.setUseCaches(true); urlConnection.connect(); return urlConnection; }
Example 12
Source Project: mobile-manager-tool File: HttpUtils.java License: MIT License | 5 votes |
/** * set HttpRequest to HttpURLConnection * * @param request source request * @param urlConnection destin url connection */ private static void setURLConnection(HttpRequest request, HttpURLConnection urlConnection) { if (request == null || urlConnection == null) { return; } setURLConnection(request.getRequestProperties(), urlConnection); if (request.getConnectTimeout() >= 0) { urlConnection.setConnectTimeout(request.getConnectTimeout()); } if (request.getReadTimeout() >= 0) { urlConnection.setReadTimeout(request.getReadTimeout()); } }
Example 13
Source Project: freeline File: UsingReportAction.java License: BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void run() { try { URL url = new URL("https://www.freelinebuild.com/api/feedback/app"); // URL url = new URL("http://localhost:3000/api/feedback/app"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); StringBuilder builder = new StringBuilder(); builder.append(URLEncoder.encode("pkg", "UTF-8")); builder.append("="); builder.append(URLEncoder.encode(packageName, "UTF-8")); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(builder.toString()); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode >= 400) { this.callback.onFailure(new Exception(conn.getResponseMessage())); } else { this.callback.onSuccess(); } conn.disconnect(); } catch (IOException e) { this.callback.onFailure(e); } }
Example 14
Source Project: springboot-admin File: HttpUtils.java License: Apache License 2.0 | 5 votes |
private static void configConnection(HttpURLConnection connection) { if (connection == null) return; connection.setReadTimeout(mReadTimeOut); connection.setConnectTimeout(mConnectTimeOut); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.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"); }
Example 15
Source Project: ontology-java-sdk File: http.java License: GNU Lesser General Public License v3.0 | 5 votes |
public static String delete(String url, String body, boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { URL u = new URL(url); HttpURLConnection http = (HttpURLConnection) u.openConnection(); http.setConnectTimeout(10000); http.setReadTimeout(10000); http.setRequestMethod("DELETE"); http.setRequestProperty("Content-Type","application/json"); if(https) { SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, new TrustManager[]{new X509()}, new SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); ((HttpsURLConnection)http).setSSLSocketFactory(ssf); } http.setDoOutput(true); http.setDoInput(true); http.connect(); try (OutputStream out = http.getOutputStream()) { out.write(body.getBytes(DEFAULT_CHARSET)); out.flush(); } StringBuilder sb = new StringBuilder(); try (InputStream is = http.getInputStream()) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, DEFAULT_CHARSET))) { String str = null; while((str = reader.readLine()) != null) { sb.append(str); str = null; } } } if (http != null) { http.disconnect(); } return sb.toString(); }
Example 16
Source Project: selenium File: UrlChecker.java License: Apache License 2.0 | 5 votes |
private HttpURLConnection connectToUrl(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT_MS); connection.setReadTimeout(READ_TIMEOUT_MS); connection.connect(); return connection; }
Example 17
Source Project: LiquidBounce File: MixinNetHandlerLoginClient.java License: GNU General Public License v3.0 | 4 votes |
@Inject(method = "handleEncryptionRequest", at = @At("HEAD"), cancellable = true) private void handleEncryptionRequest(S01PacketEncryptionRequest packetIn, CallbackInfo callbackInfo) { if(MCLeaks.isAltActive()) { final SecretKey secretkey = CryptManager.createNewSharedKey(); String s = packetIn.getServerId(); PublicKey publickey = packetIn.getPublicKey(); String s1 = (new BigInteger(CryptManager.getServerIdHash(s, publickey, secretkey))).toString(16); final Session session = MCLeaks.getSession(); final String server = ((InetSocketAddress) this.networkManager.getRemoteAddress()).getHostName() + ":" + ((InetSocketAddress) this.networkManager.getRemoteAddress()).getPort(); try { final String jsonBody = "{\"session\":\"" + session.getToken() + "\",\"mcname\":\"" + session.getUsername() + "\",\"serverhash\":\"" + s1 + "\",\"server\":\"" + server + "\"}"; final HttpURLConnection connection = (HttpURLConnection) new URL("https://auth.mcleaks.net/v1/joinserver").openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0"); connection.setDoOutput(true); final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(jsonBody.getBytes(StandardCharsets.UTF_8)); outputStream.flush(); outputStream.close(); final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final StringBuilder outputBuilder = new StringBuilder(); String line; while((line = reader.readLine()) != null) outputBuilder.append(line); reader.close(); final JsonElement jsonElement = new Gson().fromJson(outputBuilder.toString(), JsonElement.class); if(!jsonElement.isJsonObject() || !jsonElement.getAsJsonObject().has("success")) { this.networkManager.closeChannel(new ChatComponentText("Invalid response from MCLeaks API")); callbackInfo.cancel(); return; } if(!jsonElement.getAsJsonObject().get("success").getAsBoolean()) { String errorMessage = "Received success=false from MCLeaks API"; if(jsonElement.getAsJsonObject().has("errorMessage")) errorMessage = jsonElement.getAsJsonObject().get("errorMessage").getAsString(); this.networkManager.closeChannel(new ChatComponentText(errorMessage)); callbackInfo.cancel(); return; } }catch(final Exception e) { this.networkManager.closeChannel(new ChatComponentText("Error whilst contacting MCLeaks API: " + e.toString())); callbackInfo.cancel(); return; } ClientUtils.sendEncryption(networkManager, secretkey, publickey, packetIn); callbackInfo.cancel(); } }
Example 18
Source Project: ip17mon-java File: Locator.java License: MIT License | 4 votes |
public static Locator loadFromNet(String netPath) throws IOException { URL url = new URL(netPath); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setConnectTimeout(3000); httpConn.setReadTimeout(30 * 1000); int responseCode = httpConn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { return null; } int length = httpConn.getContentLength(); if (length <= 0 || length > 64 * 1024 * 1024) { throw new InputMismatchException("invalid ip data"); } InputStream is = httpConn.getInputStream(); byte[] data = new byte[length]; int downloaded = 0; int read = 0; while (downloaded < length) { try { read = is.read(data, downloaded, length - downloaded); } catch (IOException e) { is.close(); throw new IOException("read error"); } if (read < 0) { is.close(); throw new IOException("read error"); } downloaded += read; } is.close(); String path = url.getPath(); if (path.toLowerCase().endsWith("datx")) { return loadBinary(data, true); } else if (path.toLowerCase().endsWith("dat")) { return loadBinary(data, false); } else { return loadBinaryUnkown(data); } }
Example 19
Source Project: flow File: DevModeHandler.java License: Apache License 2.0 | 3 votes |
/** * Prepare a HTTP connection against webpack-dev-server. * * @param path * the file to request * @param method * the http method to use * @return the connection * @throws IOException * on connection error */ public HttpURLConnection prepareConnection(String path, String method) throws IOException { URL uri = new URL(WEBPACK_HOST + ":" + getPort() + path); HttpURLConnection connection = (HttpURLConnection) uri.openConnection(); connection.setRequestMethod(method); connection.setReadTimeout(DEFAULT_TIMEOUT); connection.setConnectTimeout(DEFAULT_TIMEOUT); return connection; }
Example 20
Source Project: SimplifyReader File: DownloadUtils.java License: Apache License 2.0 | votes |
/** * TODO 获得真实地址 * * @param segUrl * @return 302跳转后的地址 */ public static String getLocation(String segUrl) { try { URL url = new URL(segUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(20000); conn.setConnectTimeout(15000); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("HEAD"); return conn.getHeaderField("Location"); } catch (IOException e) { Logger.e(TAG, "DownloadUtils#getLocation()", e); } return null; }