當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpURLConnection.setConnectTimeout方法代碼示例

本文整理匯總了Java中java.net.HttpURLConnection.setConnectTimeout方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpURLConnection.setConnectTimeout方法的具體用法?Java HttpURLConnection.setConnectTimeout怎麽用?Java HttpURLConnection.setConnectTimeout使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.net.HttpURLConnection的用法示例。


在下文中一共展示了HttpURLConnection.setConnectTimeout方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: AddrCanConnect

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 鏈接是否可以被請求
 *
 * @param url     地址
 * @param timeout 超時,單位毫秒
 * @return true | false
 */
public static boolean AddrCanConnect(String url, int timeout) {

    if (StringUtil.isEmpty(url)) {
        return false;
    }

    boolean canConnect = false;
    try {
        URL urlStr = new URL(url);

        HttpURLConnection connection = (HttpURLConnection) urlStr.openConnection();
        connection.setUseCaches(false);
        connection.setConnectTimeout(timeout);
        int state = connection.getResponseCode();
        if (state == HttpURLConnection.HTTP_OK) {
            canConnect = true;
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return canConnect;
}
 
開發者ID:DomKing,項目名稱:springbootWeb,代碼行數:31,代碼來源:IPUtil.java

示例2: downloadApiJar

import java.net.HttpURLConnection; //導入方法依賴的package包/類
public void downloadApiJar(String urlStr) throws IOException {
  URL url = new URL(urlStr);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setConnectTimeout(3 * 1000);
  conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  conn.setRequestProperty("Authorization", "Basic " + AUTHOR);
  InputStream inputStream = conn.getInputStream();
  byte[] getData = readInputStream(inputStream);
  File saveDir = new File(API_DIR_PATH);
  if (!saveDir.exists()) {
    saveDir.mkdir();
  }
  File file = new File(API_JAR_PATH);
  file.deleteOnExit();
  FileOutputStream fos = new FileOutputStream(file);
  fos.write(getData);
  if (fos != null) {
    fos.close();
  }
  if (inputStream != null) {
    inputStream.close();
  }
  logger.info(url + " download success");
}
 
開發者ID:venus-boot,項目名稱:saluki,代碼行數:25,代碼來源:ApiJarService.java

示例3: openConnection

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:23,代碼來源:HurlStack.java

示例4: checkConnection

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * <pre>
 * 描述: 判斷服務連通性
 * @author yi.zhang
 * 時間: 2017年4月19日 下午6:00:40
 * @param url	請求URL
 * @param auth	認證信息(username+":"+password)
 * @return (true:連接成功,false:連接失敗)
 * </pre>
 */
public static boolean checkConnection(String url,String auth){
	boolean flag = false;
	try {
		HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
		connection.setConnectTimeout(5*1000);
		if(auth!=null&&!"".equals(auth)){
			String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
			connection.setRequestProperty("Authorization", authorization);
		}
		connection.connect();
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
			flag = true;
		}
		connection.disconnect();
	}catch (Exception e) {
		logger.error("--Server Connect Error !",e);
	}
	return flag;
}
 
開發者ID:dev-share,項目名稱:css-elasticsearch,代碼行數:30,代碼來源:HttpUtil.java

示例5: makeRequest

import java.net.HttpURLConnection; //導入方法依賴的package包/類
protected Response makeRequest(String url, DownZ.Method m, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.

    URL mUrl = new URL(url);
    conn = (HttpURLConnection) mUrl.openConnection();
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setConnectTimeout(TIMEOUT);
     /*  time in milliseconds */

    switch (m) {
        case GET:
            conn.setRequestMethod("GET");
            break;

        case POST:
            conn.setRequestMethod("POST");
            break;

        case PUT:
            conn.setRequestMethod("PUT");
            break;

        case DELETE:
            conn.setRequestMethod("DELETE");
            break;
    }


    conn.setDoInput(true);
    conn.setDoOutput(m != DownZ.Method.GET);


    //write headers if any
    if (headers.size() > 0) {
        for (HeaderParams header : headers) {
            conn.setRequestProperty(header.getKey(), header.getValue());
        }
    }


    Uri.Builder builder = new Uri.Builder();

    //write request parameters
    if (params.size() > 0) {
        for (RequestParams itm : params) {
            builder.appendQueryParameter(itm.getKey(), itm.getValue());
        }

        String query = builder.build().getEncodedQuery();

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();
        os.close();
    }


    conn.connect();


    int response = conn.getResponseCode();
    is = conn.getInputStream();

    Response resp = new Response();
    resp.setCode(response);
    resp.setData(is);
    return resp;
}
 
開發者ID:100rabhkr,項目名稱:DownZLibrary,代碼行數:74,代碼來源:Task.java

示例6: post

import java.net.HttpURLConnection; //導入方法依賴的package包/類
public Response post(String uri, Map<String, Object> headers, Map<String, Object> params) {
	// POST request with parameter map
	
	String requestAddress = NetworkingHelper.createRequestAddress(this.targetAddress, uri);
	// Request address with uri
	
	try {
		url = new URL(requestAddress);
		connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setDoOutput(true);
		// Enable do output
		connection.setReadTimeout(this.readTimeout);
		connection.setConnectTimeout(this.connectTimeout);
		
		if(headers != null && headers.size() > 0) {
			for(String key : headers.keySet()) {
				connection.setRequestProperty(key, (String) headers.get(key));
			}
		}
		
		if(params != null && params.size() > 0) {
               OutputStream out = connection.getOutputStream();
			out.write(NetworkingHelper.createParamBytes(params));
			// Send byte[] data if body data is exists
			out.flush();
		}
		
		return NetworkingHelper.getResponse(connection);
	} catch (IOException e) {
		e.printStackTrace();
		return null;
	}
}
 
開發者ID:JoMingyu,項目名稱:Daejeon-People,代碼行數:35,代碼來源:HttpClient.java

示例7: openConnection

import java.net.HttpURLConnection; //導入方法依賴的package包/類
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);
    if (b.a.equals(url.getProtocol()) && this.mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(this.mSslSocketFactory);
    }
    return connection;
}
 
開發者ID:JackChan1999,項目名稱:boohee_v5.6,代碼行數:13,代碼來源:MyHttpStack.java

示例8: openConnection

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@NonNull
private HttpURLConnection openConnection(Uri path) throws IOException {
    final HttpURLConnection connection = (HttpURLConnection) new URL(path.toString()).openConnection();

    connection.setConnectTimeout(BittrexApiClient.DEFAULT_CONNECT_TIMEOUT_MILLIS);
    connection.setReadTimeout(BittrexApiClient.DEFAULT_READ_TIMEOUT_MILLIS);

    return connection;
}
 
開發者ID:CoryCharlton,項目名稱:BittrexApi,代碼行數:10,代碼來源:UrlConnectionDownloader.java

示例9: openConnection

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * Opens an {@link HttpURLConnection} with parameters.
 *
 * @param request
 * @param listener
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(WXRequest request, OnHttpListener listener) throws IOException {
  URL url = new URL(request.url);
  HttpURLConnection connection = createConnection(url);
  connection.setConnectTimeout(request.timeoutMs);
  connection.setReadTimeout(request.timeoutMs);
  connection.setUseCaches(false);
  connection.setDoInput(true);

  if (request.paramMap != null) {
    Set<String> keySets = request.paramMap.keySet();
    for (String key : keySets) {
      connection.addRequestProperty(key, request.paramMap.get(key));
    }
  }

  if ("POST".equals(request.method) || "PUT".equals(request.method) || "PATCH".equals(request.method)) {
    connection.setRequestMethod(request.method);
    if (request.body != null) {
      if (listener != null) {
        listener.onHttpUploadProgress(0);
      }
      connection.setDoOutput(true);
      DataOutputStream out = new DataOutputStream(connection.getOutputStream());
      //TODO big stream will cause OOM; Progress callback is meaningless
      out.write(request.body.getBytes());
      out.close();
      if (listener != null) {
        listener.onHttpUploadProgress(100);
      }
    }
  } else if (!TextUtils.isEmpty(request.method)) {
    connection.setRequestMethod(request.method);
  } else {
    connection.setRequestMethod("GET");
  }

  return connection;
}
 
開發者ID:erguotou520,項目名稱:weex-uikit,代碼行數:47,代碼來源:DefaultWXHttpAdapter.java

示例10: post

import java.net.HttpURLConnection; //導入方法依賴的package包/類
public Response post(String uri, Map<String, Object> headers, JSONObject requestObject) {
	// POST request with JSON data
	
	String requestAddress = NetworkingHelper.createRequestAddress(this.targetAddress, uri);
	// Request address with uri
	
	try {
		url = new URL(requestAddress);
		connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setDoOutput(true);
		// Enable do output
		connection.setReadTimeout(this.readTimeout);
		connection.setConnectTimeout(this.connectTimeout);
		
		if(headers != null && headers.size() > 0) {
			for(String key : headers.keySet()) {
				connection.setRequestProperty(key, (String) headers.get(key));
			}
		}
		
		wr = new OutputStreamWriter(connection.getOutputStream());
		wr.write(requestObject.toString());
		wr.flush();
		
		return NetworkingHelper.getResponse(connection);
	} catch (IOException e) {
		e.printStackTrace();
		return null;
	}
}
 
開發者ID:JoMingyu,項目名稱:Server-Quickstart-Vert.x,代碼行數:32,代碼來源:HttpClient.java

示例11: get

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 鍙戦�丟et璿鋒眰
 * @param url
 * @return
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws IOException 
 * @throws KeyManagementException 
 */
public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
	if(enableSSL){
		return get(url,true);
	}else{
		StringBuffer bufferRes = null;
        URL urlGet = new URL(url);
        HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
        // 榪炴帴瓚呮椂
        http.setConnectTimeout(25000);
        // 璿誨彇瓚呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
        http.setReadTimeout(25000);
        http.setRequestMethod("GET");
        http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();
        
        InputStream in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
        String valueString = null;
        bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null){
            bufferRes.append(valueString);
        }
        in.close();
        if (http != null) {
            // 鍏抽棴榪炴帴
            http.disconnect();
        }
        return bufferRes.toString();
	}
}
 
開發者ID:bubicn,項目名稱:bubichain-sdk-java,代碼行數:42,代碼來源:HttpKit.java

示例12: urlRequest

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * @param url 請求URL
 * @param method 請求URL
 * @param param	json參數(post|put)
 * @param auth	認證(username+:+password)
 * @return 返回結果
 */
public static String urlRequest(String url,String method,String param,String auth){
	String result = null;
	try {
		HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
		connection.setConnectTimeout(60*1000);
		connection.setRequestMethod(method.toUpperCase());
		if(auth!=null&&!"".equals(auth)){
			String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
			connection.setRequestProperty("Authorization", authorization);
		}
		if(param!=null&&!"".equals(param)){
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();
			DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
			dos.write(param.getBytes(Consts.UTF_8));
			dos.flush();
			dos.close();
		}else{
			connection.connect();
		}
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK||connection.getResponseCode()==HttpURLConnection.HTTP_CREATED){
			InputStream in = connection.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int len = 0;
			while((len=in.read(buff, 0, buff.length))>0){
				out.write(buff, 0, len);
			}
			byte[] data = out.toByteArray();
			in.close();
			result = data!=null&&data.length>0?new String(data, Consts.UTF_8):null;
		}else{
			result = "{\"status\":"+connection.getResponseCode()+",\"msg\":\""+connection.getResponseMessage()+"\"}";
		}
		connection.disconnect();
	}catch (Exception e) {
		logger.error("--http request error !",e);
	}
	return result;
}
 
開發者ID:dev-share,項目名稱:css-elasticsearch,代碼行數:49,代碼來源:HttpUtil.java

示例13: getImageStream

import java.net.HttpURLConnection; //導入方法依賴的package包/類
public static InputStream getImageStream(String path) throws Exception {
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5 * 1000);
    conn.setRequestMethod("GET");
    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        return conn.getInputStream();
    }
    return null;
}
 
開發者ID:wangzhaosheng,項目名稱:publicProject,代碼行數:11,代碼來源:ImageUtils.java

示例14: urlRequest

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * @param url 請求URL
 * @param method 請求URL
 * @param param	json參數(post|put)
 * @return
 */
public static String urlRequest(String url,String method,String param,String auth){
	String result = null;
	try {
		HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
		connection.setConnectTimeout(60*1000);
		connection.setRequestMethod(method.toUpperCase());
		if(auth!=null&&!"".equals(auth)){
			String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
			connection.setRequestProperty("Authorization", authorization);
		}
		if(param!=null&&!"".equals(param)){
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();
			DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
			dos.write(param.getBytes(Consts.UTF_8));
			dos.flush();
			dos.close();
		}else{
			connection.connect();
		}
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
			InputStream in = connection.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int len = 0;
			while((len=in.read(buff, 0, buff.length))>0){
				out.write(buff, 0, len);
			}
			byte[] data = out.toByteArray();
			in.close();
			result = data!=null&&data.length>0?new String(data, Consts.UTF_8):null;
		}else{
			result = "{\"status\":"+connection.getResponseCode()+",\"msg\":\""+connection.getResponseMessage()+"\"}";
		}
		connection.disconnect();
	}catch (Exception e) {
		logger.error("--http request error !",e);
	}
	return result;
}
 
開發者ID:dev-share,項目名稱:database-transform-tool,代碼行數:48,代碼來源:HttpUtil.java

示例15: get

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 鍙戦�丟et璿鋒眰
 *
 * @param url
 * @return
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws KeyManagementException
 */
public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException{
    if (enableSSL) {
        return get(url, true);
    } else {
        StringBuffer bufferRes = null;
        URL urlGet = new URL(url);
        HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
        // 榪炴帴瓚呮椂
        http.setConnectTimeout(25000);
        // 璿誨彇瓚呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
        http.setReadTimeout(25000);
        http.setRequestMethod("GET");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        InputStream in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
        String valueString = null;
        bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }
        in.close();
        if (http != null) {
            // 鍏抽棴榪炴帴
            http.disconnect();
        }
        return bufferRes.toString();
    }
}
 
開發者ID:bubicn,項目名稱:bubichain-sdk-java,代碼行數:43,代碼來源:HttpKit.java


注:本文中的java.net.HttpURLConnection.setConnectTimeout方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。