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


Java URLConnection.setConnectTimeout方法代碼示例

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


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

示例1: checkRedirect

import java.net.URLConnection; //導入方法依賴的package包/類
private static URLConnection checkRedirect(URLConnection conn, int timeout) throws IOException {
    if (conn instanceof HttpURLConnection) {
        conn.connect();
        int code = ((HttpURLConnection) conn).getResponseCode();
        if (code == HttpURLConnection.HTTP_MOVED_TEMP
                || code == HttpURLConnection.HTTP_MOVED_PERM) {
            // in case of redirection, try to obtain new URL
            String redirUrl = conn.getHeaderField("Location"); //NOI18N
            if (null != redirUrl && !redirUrl.isEmpty()) {
                //create connection to redirected url and substitute original conn
                URL redirectedUrl = new URL(redirUrl);
                URLConnection connRedir = redirectedUrl.openConnection();
                // XXX is this neede
                connRedir.setRequestProperty("User-Agent", "NetBeans"); // NOI18N
                connRedir.setConnectTimeout(timeout);
                connRedir.setReadTimeout(timeout);
                if (connRedir instanceof HttpsURLConnection) {
                    NetworkAccess.initSSL((HttpsURLConnection) connRedir);
                }
                return connRedir;
            }
        }
    }
    return conn;
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:26,代碼來源:NetworkAccess.java

示例2: createConnectionToURL

import java.net.URLConnection; //導入方法依賴的package包/類
/**
 * Create URLConnection instance.
 *
 * @param url            to what url
 * @param requestHeaders additional request headers
 * @return connection instance
 * @throws IOException when url is invalid or failed to establish connection
 */
public static URLConnection createConnectionToURL(final String url, final Map<String, String> requestHeaders) throws IOException {
    final URL connectionURL = URLUtility.stringToUrl(url);
    if (connectionURL == null) {
        throw new IOException("Invalid url format: " + url);
    }

    final URLConnection urlConnection = connectionURL.openConnection();
    urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
    urlConnection.setReadTimeout(READ_TIMEOUT);

    if (requestHeaders != null) {
        for (final Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    return urlConnection;
}
 
開發者ID:SUTFutureCoder,項目名稱:localcloud_fe,代碼行數:27,代碼來源:URLConnectionHelper.java

示例3: handleImageContent

import java.net.URLConnection; //導入方法依賴的package包/類
public TextMessage handleImageContent(String id){
    String filepath = new File("/opt/tomcat/webapps/ROOT/downloaded.jpg").getAbsolutePath();
    file = new File(filepath);
    try {
        URL urlP = new URL("https://api.line.me/v2/bot/message/" + id + "/content");
        URLConnection conn = urlP.openConnection();
        conn.setRequestProperty("Authorization", "Bearer {ZzEeHlFeiIA/C4TUvl3E/IuYW8TIBEdAr3xzZCgHuURivuycKWOiPGBp5oFqLyHSh/YkUFgm4eGGkVuo4WkOvhUwKdgCbFnO6ltoV/oMU7uJaZAbgM+RqeTo8LAbdjlId0TGTdPe6H0QyfzzoJyppgdB04t89/1O/w1cDnyilFU=}");
        conn.setConnectTimeout(5 * 1000); // Tak tambahin sendiri
        BufferedImage img = ImageIO.read(conn.getInputStream());
        ImageIO.write(img, "jpg", file);
    } catch (Exception e) {
        e.printStackTrace();
    }
    byte[] buff = getBytesFromFile(file);
    String response_faceAPI = doFacePlusAPI(buff);
    TextMessage textMessage;
    textMessage = processJsonFaceApi(response_faceAPI);
    return textMessage;
}
 
開發者ID:axellageraldinc,項目名稱:lj-line-bot,代碼行數:20,代碼來源:FaceDetector.java

示例4: netCheck

import java.net.URLConnection; //導入方法依賴的package包/類
public static boolean netCheck(String[] testURLs) {
	for (String testURL : testURLs) {
		try {
       	   URL url = new URL(testURL);
       	   URLConnection conn = (URLConnection)url.openConnection();
       	   conn.setConnectTimeout(TemplateConstants.CONN_SHORT_TIMEOUT);
       	   conn.setReadTimeout(TemplateConstants.READ_SHORT_TIMEOUT);
       	   conn.getContent();
       	   return true;
		} catch (Exception e) {              
			System.out.println("failed to connect to " + testURL);
		}
	}
	
       return false;
}
 
開發者ID:max6cn,項目名稱:jmt,代碼行數:17,代碼來源:ConnectionCheck.java

示例5: refresh

import java.net.URLConnection; //導入方法依賴的package包/類
public static boolean refresh(){
	props 							= new Properties();
	try {
		URLConnection connection	= new URL("http://kussmaul.net/projects.properties").openConnection();
		connection.setConnectTimeout(1000);
		final InputStream in = connection.getInputStream();
		props.load(in);
		if(!props.containsKey("ServerIP"))
			throw new Exception("Something wrong with download");
		in.close();
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		props						= getDefaultProperties();
		return false;
	}
}
 
開發者ID:CalebKussmaul,項目名稱:GIFKR,代碼行數:18,代碼來源:CalebKussmaul.java

示例6: resolve

import java.net.URLConnection; //導入方法依賴的package包/類
/**
 * @param type the ec2 hostname type to discover.
 * @return the appropriate host resolved from ec2 meta-data, or null if it cannot be obtained.
 * @see CustomNameResolver#resolveIfPossible(String)
 */
@SuppressForbidden(reason = "We call getInputStream in doPrivileged and provide SocketPermission")
public InetAddress[] resolve(Ec2HostnameType type) throws IOException {
    InputStream in = null;
    String metadataUrl = AwsEc2ServiceImpl.EC2_METADATA_URL + type.ec2Name;
    try {
        URL url = new URL(metadataUrl);
        logger.debug("obtaining ec2 hostname from ec2 meta-data url {}", url);
        URLConnection urlConnection = SocketAccess.doPrivilegedIOException(url::openConnection);
        urlConnection.setConnectTimeout(2000);
        in = SocketAccess.doPrivilegedIOException(urlConnection::getInputStream);
        BufferedReader urlReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

        String metadataResult = urlReader.readLine();
        if (metadataResult == null || metadataResult.length() == 0) {
            throw new IOException("no gce metadata returned from [" + url + "] for [" + type.configName + "]");
        }
        // only one address: because we explicitly ask for only one via the Ec2HostnameType
        return new InetAddress[] { InetAddress.getByName(metadataResult) };
    } catch (IOException e) {
        throw new IOException("IOException caught when fetching InetAddress from [" + metadataUrl + "]", e);
    } finally {
        IOUtils.closeWhileHandlingException(in);
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:30,代碼來源:Ec2NameResolver.java

示例7: get

import java.net.URLConnection; //導入方法依賴的package包/類
/***
 * get請求mcrmbAPI
 * @param url API
 * @param reason 理由
 * @return json
 * @throws Exception HTTP請求異常
 */
public static JsonObject get(String url, String reason) throws IOException {
    if (McrmbPluginInfo.config.logApi) {
        McrmbCoreMain.info("發起" + reason + "請求: " + api + url);
    }
    StringBuilder builder = new StringBuilder();
    URLConnection con = new URL(api + url).openConnection();
    con.setRequestProperty("User-Agent", java_version);
    con.setRequestProperty("OS-Info", os);
    con.setConnectTimeout(25000);
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }
    reader.close();
    return new JsonParser().parse(builder.toString()).getAsJsonObject();
}
 
開發者ID:txgs888,項目名稱:McrmbCore_Sponge,代碼行數:25,代碼來源:HttpUtil.java

示例8: getBitmapFromUrl

import java.net.URLConnection; //導入方法依賴的package包/類
private Bitmap getBitmapFromUrl(String url) {
    Bitmap bitmap = null;
    try {
        URLConnection conn = new URL(url).openConnection();
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        bitmap = BitmapFactory.decodeStream((InputStream) conn.getContent());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bitmap;
}
 
開發者ID:ahmed-adel-said,項目名稱:SimpleNetworkLibrary,代碼行數:13,代碼來源:ImageSingleRequest.java

示例9: createURLConnection

import java.net.URLConnection; //導入方法依賴的package包/類
public static URLConnection createURLConnection(String url) {
    try {
        final URL           address    = new URL(url);
        final URLConnection connection = address.openConnection();
        connection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0");
        connection.setConnectTimeout(5000);
        connection.setRequestProperty("Content-Type", "image/png");
        return connection;
    } catch (IOException ex) {
        System.out.println("Error creating connection!");
        ex.printStackTrace();
    }
    return null;
}
 
開發者ID:Parabot,項目名稱:Parabot-317-API-Minified-OS-Scape,代碼行數:16,代碼來源:NetUtil.java

示例10: getUpdateProperties

import java.net.URLConnection; //導入方法依賴的package包/類
private Properties getUpdateProperties(URL updateUrl) throws IOException {
  URLConnection connection = updateUrl.openConnection();
  connection.setConnectTimeout(3 * 1000);
  InputStream in = connection.getInputStream();
  try {
    Properties props = new Properties();
    props.load(connection.getInputStream());
    return props;
  } finally {
    if (in != null) {
      in.close();
    }
  }
}
 
開發者ID:AsuraTeam,項目名稱:asura,代碼行數:15,代碼來源:UpdateChecker.java

示例11: save

import java.net.URLConnection; //導入方法依賴的package包/類
/**
 * 上傳文件
 * 
 * @throws IllegalStateException
 * @throws IOException
 */
protected void save() throws IllegalStateException, IOException {

	// 構造URL
	URL url = new URL(fileUrl);

	// 打開連接
	URLConnection con = url.openConnection();

	// 設置請求超時為5s
	con.setConnectTimeout(5 * 1000);

	// 輸入流
	InputStream is = con.getInputStream();

	// 1K的數據緩衝
	byte[] bs = new byte[1024];

	// 讀取到的數據長度
	int len;

	// 獲取文件mime類型
	contentType = con.getContentType();

	// 通過Mime類型獲取文件類型
	fileSuffix = ContentTypeUtil.getFileTypeByMimeType(contentType);

	// 路徑
	path = UploadUtil.getPath(fileSuffix);

	// 文件名
	filename = UploadUtil.getFileName();

	// 全路徑
	filePath = path + filename + "." + fileSuffix;

	// 訪問地址
	webURL = UploadUtil.getURL(fileSuffix) + filename + "." + fileSuffix;

	// 輸出的文件流
	OutputStream os = new FileOutputStream(filePath);

	// 開始讀取
	while ((len = is.read(bs)) != -1) {
		os.write(bs, 0, len);
	}

	// 完畢,關閉所有鏈接
	os.close();
	is.close();
	
	isUpload = true;
}
 
開發者ID:ZiryLee,項目名稱:FileUpload2Spring,代碼行數:59,代碼來源:DownloadEntityImp.java

示例12: downloadFully

import java.net.URLConnection; //導入方法依賴的package包/類
public static void downloadFully(URL url, File target, JProgressBar progressBar) throws IOException {

        // We don't use the settings here explicitly, since HttpRequests picks up the network settings from studio directly.
        try {
            URLConnection connection = url.openConnection();
            if (connection instanceof HttpsURLConnection) {
                ((HttpsURLConnection) connection).setInstanceFollowRedirects(true);
                ((HttpsURLConnection) connection).setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
                ((HttpsURLConnection) connection).setRequestProperty("Accept-Charset", "UTF-8");
                ((HttpsURLConnection) connection).setDoOutput(true);
                ((HttpsURLConnection) connection).setDoInput(true);
            }
            connection.setConnectTimeout(3000);
            connection.connect();
            int contentLength = connection.getContentLength();
            if (contentLength < 1) {
                throw new FileNotFoundException();
            }
            if (progressBar != null) {
                progressBar.setMinimum(0);
                progressBar.setMaximum(contentLength);
            }
            OutputStream dest = new FileOutputStream(target);
            InputStream in = connection.getInputStream();
            int count;
            int done = 0;
            byte data[] = new byte[BUFFER_SIZE];
            while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
                done += count;
                if (progressBar != null) {
                    progressBar.setValue(done);
                }
                dest.write(data, 0, count);
            }
            dest.close();
            in.close();
        } finally {
            if (target.length() == 0) {
                try {
                    target.delete();
                } catch (Exception e) {
                }
            }
        }
    }
 
開發者ID:NBANDROIDTEAM,項目名稱:NBANDROID-V2,代碼行數:46,代碼來源:MavenDownloader.java

示例13: connect

import java.net.URLConnection; //導入方法依賴的package包/類
/** 
 * The connection establishment is attempted multiple times and is given up 
 * only on the last failure. Instead of connecting with a timeout of 
 * X, we try connecting with a timeout of x < X but multiple times. 
 */
private void connect(URLConnection connection, int connectionTimeout)
throws IOException {
  int unit = 0;
  if (connectionTimeout < 0) {
    throw new IOException("Invalid timeout "
                          + "[timeout = " + connectionTimeout + " ms]");
  } else if (connectionTimeout > 0) {
    unit = Math.min(UNIT_CONNECT_TIMEOUT, connectionTimeout);
  }
  long startTime = Time.monotonicNow();
  long lastTime = startTime;
  int attempts = 0;
  // set the connect timeout to the unit-connect-timeout
  connection.setConnectTimeout(unit);
  while (true) {
    try {
      attempts++;
      connection.connect();
      break;
    } catch (IOException ioe) {
      long currentTime = Time.monotonicNow();
      long retryTime = currentTime - startTime;
      long leftTime = connectionTimeout - retryTime;
      long timeSinceLastIteration = currentTime - lastTime;
      // throw an exception if we have waited for timeout amount of time
      // note that the updated value if timeout is used here
      if (leftTime <= 0) {
        int retryTimeInSeconds = (int) retryTime/1000;
        LOG.error("Connection retry failed with " + attempts + 
            " attempts in " + retryTimeInSeconds + " seconds");
        throw ioe;
      }
      // reset the connect timeout for the last try
      if (leftTime < unit) {
        unit = (int)leftTime;
        // reset the connect time out for the final connect
        connection.setConnectTimeout(unit);
      }
      
      if (timeSinceLastIteration < unit) {
        try {
          // sleep the left time of unit
          sleep(unit - timeSinceLastIteration);
        } catch (InterruptedException e) {
          LOG.warn("Sleep in connection retry get interrupted.");
          if (stopped) {
            return;
          }
        }
      }
      // update the total remaining connect-timeout
      lastTime = Time.monotonicNow();
    }
  }
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:61,代碼來源:Fetcher.java

示例14: updateData

import java.net.URLConnection; //導入方法依賴的package包/類
public void updateData(ResultBeatmap rb) {
    if (!rb.equals(lastMap)){
        lastMap = rb;
        
        lblImg.setIcon(null);

        lblImg.setText("Waiting...");
        lblImg.setText("");
        
        lblName.setText(decode(rb.getArtist()) + " - " + decode(rb.getTitle()));
        lblCreator.setText(decode(rb.getCreator()));
        lblStatus.setText("Status not implemented");
        
        String tagsStr = "";
        String[] tags = rb.getTags();
        for (int i = 0; i < tags.length; i++){
            tagsStr += tags[i];
            
            if (i != tags.length - 1){
                tagsStr += ", ";
            }
        }
        
        lblTags.setText("Tags: " + tagsStr);
        
        if (rb.getThumbData().isEmpty()){
            try {
                lblImg.setForeground(Color.BLACK);
                lblImg.setText("Loading thumb...");
                
                URL url = new URL(rb.getThumbUrl());
                URLConnection conn = url.openConnection();
                
                conn.setConnectTimeout(100);
                conn.setReadTimeout(100);
                
                lblImg.setText("");
                lblImg.setIcon(new ImageIcon(ImageIO.read(conn.getInputStream())));
            } catch (Exception e){
                lblImg.setForeground(Color.RED);
                lblImg.setText("Thumb Fetch Error");
            }
        } else {
            lblImg.setIcon(new ImageIcon(Base64.decodeBase64(rb.getThumbData())));
        }
    }
}
 
開發者ID:mob41,項目名稱:osumer,代碼行數:48,代碼來源:ResultBeatmapCell.java

示例15: createAUResolver

import java.net.URLConnection; //導入方法依賴的package包/類
/** Entity resolver that knows about AU DTDs, so no network is needed.
 * @author Jesse Glick
 */
public static EntityResolver createAUResolver() {
    return new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicID, String systemID) throws IOException, SAXException {
            if ("-//NetBeans//DTD Autoupdate Catalog 1.0//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-1_0.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Module Info 1.0//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-1_0.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Catalog 2.0//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_0.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Module Info 2.0//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_0.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Catalog 2.2//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_2.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Module Info 2.2//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_2.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Catalog 2.3//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_3.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Module Info 2.3//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_3.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Catalog 2.4//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_4.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Module Info 2.4//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_4.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Catalog 2.5//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_5.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Module Info 2.5//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_5.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Catalog 2.6//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_6.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Catalog 2.7//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_7.dtd").toString()); // NOI18N
            } else if ("-//NetBeans//DTD Autoupdate Module Info 2.7//EN".equals(publicID)) { // NOI18N
                return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_7.dtd").toString()); // NOI18N
            } else {
                if (systemID.endsWith(".dtd")) { // NOI18N
                    return new InputSource(new ByteArrayInputStream(new byte[0]));
                }
                URL u = new URL(systemID);
                URLConnection oc = u.openConnection();
                oc.setConnectTimeout(5000);
                return new InputSource(oc.getInputStream());
            }
        }
    };
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:50,代碼來源:XMLUtil.java


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