java.net.HttpURLConnection#setReadTimeout ( )源码实例Demo

下面列出了java.net.HttpURLConnection#setReadTimeout ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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;
    }
}
 
源代码2 项目: jease   文件: Urls.java
/**
 * 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;
}
 
/**
 * 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;
}
 
源代码4 项目: openjdk-jdk8u   文件: B6401598.java
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;
        }
 
@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;
}
 
源代码6 项目: AndroidWallet   文件: StringUtils.java
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;
}
 
源代码7 项目: FeedListViewDemo   文件: HurlStack.java
/**
 * 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;
}
 
源代码8 项目: openjdk-8   文件: B6401598.java
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;
        }
 
@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);
}
 
源代码10 项目: ontology-java-sdk   文件: http.java
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();
}
 
源代码11 项目: airsonic   文件: InternetRadioService.java
/**
 * 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;
}
 
源代码12 项目: mobile-manager-tool   文件: HttpUtils.java
/**
 * 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());
    }
}
 
源代码13 项目: freeline   文件: UsingReportAction.java
@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);
            }
        }
 
源代码14 项目: springboot-admin   文件: HttpUtils.java
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");
}
 
源代码15 项目: ontology-java-sdk   文件: http.java
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();
}
 
源代码16 项目: selenium   文件: UrlChecker.java
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;
}
 
源代码17 项目: LiquidBounce   文件: MixinNetHandlerLoginClient.java
@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();
    }
}
 
源代码18 项目: ip17mon-java   文件: Locator.java
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);
    }
}
 
源代码19 项目: flow   文件: DevModeHandler.java
/**
 * 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;
}
 
源代码20 项目: SimplifyReader   文件: DownloadUtils.java
/**
	 * 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;
	}