当前位置: 首页>>代码示例>>Java>>正文


Java URLConnection.connect方法代码示例

本文整理汇总了Java中java.net.URLConnection.connect方法的典型用法代码示例。如果您正苦于以下问题:Java URLConnection.connect方法的具体用法?Java URLConnection.connect怎么用?Java URLConnection.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.net.URLConnection的用法示例。


在下文中一共展示了URLConnection.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: load

import java.net.URLConnection; //导入方法依赖的package包/类
public TemplateLoader load()
{
    try
    {
        URLConnection urlConnection = new URL(url).openConnection();
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
        urlConnection.setUseCaches(false);
        urlConnection.connect();
        Files.copy(urlConnection.getInputStream(), Paths.get(dest));
        ((HttpURLConnection)urlConnection).disconnect();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return this;
}
 
开发者ID:Dytanic,项目名称:CloudNet,代码行数:17,代码来源:TemplateLoader.java

示例2: syncWebTime

import java.net.URLConnection; //导入方法依赖的package包/类
private void syncWebTime() {
    try {
        long localBeforeTime = System.currentTimeMillis();
        URL url = new URL(webTimeUrl);
        URLConnection connection = url.openConnection();
        connection.connect();
        long netTime = connection.getDate();

        long localEndTime = System.currentTimeMillis();

        netTimeOffset = (netTime + (localEndTime - localBeforeTime) / 2) - localEndTime;

        lastSyncTime = localEndTime;
    } catch (IOException e) {
        // 1 minute later try again
        lastSyncTime = lastSyncTime + 60000L;
    }
}
 
开发者ID:nuls-io,项目名称:nuls,代码行数:19,代码来源:TimeService.java

示例3: announce

import java.net.URLConnection; //导入方法依赖的package包/类
private void announce(String trackerURL,byte[] hash,byte[] peerId,int port) {
  try {
    String strUrl = trackerURL
    	+ "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20")
    	+ "&peer_id="   + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20")
    	+ "&port=" + port
    	+ "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1";
    //System.out.println(strUrl);
    URL url = new URL(strUrl);
    URLConnection con = url.openConnection();
    con.connect();
    con.getContent();
  } catch(Exception e) {
    e.printStackTrace();
  }
}
 
开发者ID:BiglySoftware,项目名称:BiglyBT,代码行数:17,代码来源:TrackerLoadTester.java

示例4: access

import java.net.URLConnection; //导入方法依赖的package包/类
/** access a url, ignoring some IOException such as the page does not exist */
static void access(String urlstring) throws IOException {
  LOG.warn("access " + urlstring);
  URL url = new URL(urlstring);
  
  URLConnection connection = url.openConnection();
  connection.connect();
  
  try {
    BufferedReader in = new BufferedReader(new InputStreamReader(
        connection.getInputStream()));
    try {
      for(; in.readLine() != null; );
    } finally {
      in.close();
    }
  } catch(IOException ioe) {
    LOG.warn("urlstring=" + urlstring, ioe);
  }
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:21,代码来源:TestPathFilter.java

示例5: handleInput

import java.net.URLConnection; //导入方法依赖的package包/类
@Override
public void handleInput(Document data, PacketSender packetSender)
{
    try
    {
        URLConnection url = new java.net.URL(data.getString("url")).openConnection();
        url.connect();
        if(System.getProperty("os.name").toLowerCase().contains("windows"))
        {
            Files.copy(url.getInputStream(), Paths.get("CloudNet-Wrapper-" + NetworkUtils.RANDOM.nextLong() + ".jar"));
        }
        else
        {
            Files.copy(url.getInputStream(), Paths.get("CloudNet-Wrapper.jar"));
        }
    }catch (Exception ex){
        ex.printStackTrace();
    }
}
 
开发者ID:Dytanic,项目名称:CloudNet,代码行数:20,代码来源:PacketInInstallUpdate.java

示例6: access

import java.net.URLConnection; //导入方法依赖的package包/类
/** access a url, ignoring some IOException such as the page does not exist */
static void access(String urlstring) throws IOException {
  LOG.warn("access " + urlstring);
  URL url = new URL(urlstring);
  URLConnection connection = url.openConnection();
  connection.connect();
  
  try {
    BufferedReader in = new BufferedReader(new InputStreamReader(
        connection.getInputStream()));
    try {
      for(; in.readLine() != null; );
    } finally {
      in.close();
    }
  } catch(IOException ioe) {
    LOG.warn("urlstring=" + urlstring, ioe);
  }
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:20,代码来源:TestGlobalFilter.java

示例7: testConnect

import java.net.URLConnection; //导入方法依赖的package包/类
@Test(dataProvider = "urls")
public void testConnect(String urlString, boolean exists) throws Exception {
    URL url = new URL(urlString);
    URLConnection uc = url.openConnection();
    try {
        uc.connect();
        if (!exists) fail("IOException expected");
    } catch (IOException ioe) {
        if (exists) fail("IOException not expected");
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:12,代码来源:Basic.java

示例8: getUrlAsString

import java.net.URLConnection; //导入方法依赖的package包/类
public static String getUrlAsString(String url) throws IOException {
  File file = new File(url);
  if (file.isFile()) {
    byte[] encoded = Files.readAllBytes(Paths.get(url));
    return new String(encoded, StandardCharsets.UTF_8);
  }

  URL urlObj = new URL(url);
  URLConnection con = urlObj.openConnection();

  con.setDoOutput(true);
  con.connect();

  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

  StringBuilder response = new StringBuilder();
  String inputLine;

  String newLine = System.getProperty("line.separator");
  while ((inputLine = in.readLine()) != null) {
    response.append(inputLine + newLine);
  }

  in.close();

  return response.toString();
}
 
开发者ID:jomof,项目名称:cdep,代码行数:28,代码来源:WebUtils.java

示例9: parse

import java.net.URLConnection; //导入方法依赖的package包/类
private void parse(URL file, TrackingHandler handler) {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        URLConnection connection = file.openConnection();
        connection.connect();
        this.lastModified = Math.max(this.lastModified, connection.getLastModified());
        saxParser.parse(connection.getInputStream(), handler);

    }
    catch (Exception ex) {
        throw new RuntimeException("Error parsing XML file " + handler.getLineNumberString(), ex);
    }
}
 
开发者ID:salesforce,项目名称:grammaticus,代码行数:16,代码来源:GrammaticalLabelFileParser.java

示例10: run

import java.net.URLConnection; //导入方法依赖的package包/类
@Override
public void run(OptionSet obj)
{
    if(obj.has("installWrapper"))
    {
        if(!Files.exists(Paths.get("wrapper")))
        {

            try
            {
                Files.createDirectories(Paths.get("wrapper"));
                System.out.println("Downloading wrapper...");
                URLConnection urlConnection = new URL(WebClient.DEFAULT_URL + "cloud/wrapper").openConnection();
                urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
                urlConnection.connect();
                Files.copy(urlConnection.getInputStream(), Paths.get("wrapper/CloudNet-Wrapper.jar"));
                System.out.println("Download completed!");
            } catch (Exception ex)
            {
                System.out.println("Error on setting up wrapper: " + ex.getMessage());
                return;
            }
        }

        try
        {
            process = new ProcessBuilder("java", "-Xmx256M", "-jar", "CloudNet-Wrapper.jar").directory(new File("wrapper")).inheritIO().start();
            Runtime.getRuntime().addShutdownHook(new Thread(process::destroy));
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
 
开发者ID:Dytanic,项目名称:CloudNet,代码行数:35,代码来源:LocalCloudWrapper.java

示例11: getContentAsString

import java.net.URLConnection; //导入方法依赖的package包/类
static String getContentAsString(URL url, Charset charset) {
    String filePath = url.getPath();
    String cachedContent = HELP_FILES_CACHE.get(filePath);
    if(cachedContent != null) {
        return cachedContent;
    }

    if (charset == null) {
        charset = Charset.defaultCharset();
    }
    try {
        URLConnection con = url.openConnection();
        con.connect();
        Reader r = new InputStreamReader(new BufferedInputStream(con.getInputStream()), charset);
        char[] buf = new char[2048];
        int read;
        StringBuilder content = new StringBuilder();
        while ((read = r.read(buf)) != -1) {
            content.append(buf, 0, read);
        }
        r.close();
        String strContent = content.toString();
        HELP_FILES_CACHE.put(filePath, strContent);
        return strContent;
    } catch (IOException ex) {
        Logger.getLogger(HtmlDocumentation.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:31,代码来源:HtmlDocumentation.java

示例12: testConnect

import java.net.URLConnection; //导入方法依赖的package包/类
static void testConnect() {
    InputStream inputStream = null;
    try {
        URL url = webUrl;

        URLConnection conn = url.openConnection();
        conn.connect();
        inputStream = conn.getInputStream();
        byte[] b = new byte[inputStream.available()];
        for (int j = 0; j < b.length; j++) {
            b[j] = (byte) inputStream.read();
        }
        String s = new String(b);
        System.out.println("Length: " + s.length());
        System.out.println(s);
    } catch (Exception ex) {
          throw new RuntimeException(ex);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:28,代码来源:HttpNegotiateServer.java

示例13: upstreamRunning

import java.net.URLConnection; //导入方法依赖的package包/类
private static boolean upstreamRunning() {
    try {
        URL url = new URL("http://localhost:" + UPSTREAM_SERVICE_PORT + "/health");
        URLConnection uc = url.openConnection();
        uc.connect();
        String status = uc.getHeaderField(0);
        return status.contains("200");

    } catch (Exception e) {
        return false;
    }
}
 
开发者ID:Kroger-Technology,项目名称:Snow-Globe,代码行数:13,代码来源:UpstreamUtil.java

示例14: getInputStreamOfURL

import java.net.URLConnection; //导入方法依赖的package包/类
public InputStream getInputStreamOfURL(URL downloadURL, Proxy proxy) throws IOException{
    
    URLConnection ucn = null;
    
    // loop until no more redirections are 
    for (;;) {
        if (Thread.currentThread().isInterrupted()) {
            return null;
        }
        if(proxy != null) {
            ucn = downloadURL.openConnection(proxy);
        } else {
            ucn = downloadURL.openConnection();
        }
        HttpURLConnection hucn = doConfigureURLConnection(ucn);

        if(Thread.currentThread().isInterrupted())
            return null;
    
        ucn.connect();

        int rc = hucn.getResponseCode();
        boolean isRedirect = 
                rc == HttpURLConnection.HTTP_MOVED_TEMP ||
                rc == HttpURLConnection.HTTP_MOVED_PERM;
        if (!isRedirect) {
            break;
        }

        String addr = hucn.getHeaderField(HTTP_REDIRECT_LOCATION);
        URL newURL = new URL(addr);
        if (!downloadURL.getProtocol().equalsIgnoreCase(newURL.getProtocol())) {
            throw new ResourceRedirectException(newURL);
        }
        downloadURL = newURL;
    }

    ucn.setReadTimeout(10000);
    InputStream is = ucn.getInputStream();
    streamLength = ucn.getContentLength();
    effectiveURL = ucn.getURL();
    return is;
    
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:45,代码来源:URLResourceRetriever.java

示例15: retreiveMetadata

import java.net.URLConnection; //导入方法依赖的package包/类
synchronized private void retreiveMetadata() throws IOException {
    URLConnection con = streamUrl.openConnection();
    con.setRequestProperty("Icy-MetaData", "1");
    con.setRequestProperty("Connection", "close");
    con.setRequestProperty("Accept", null);
    con.connect();
    int metaDataOffset = 0;
    Map<String, List<String>> headers = con.getHeaderFields();
    InputStream stream = con.getInputStream();

    if (headers.containsKey("icy-metaint")) {
        // Headers are sent via HTTP
        metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
    } else {
        // Headers are sent within a stream
        StringBuilder strHeaders = new StringBuilder();
        char c;
        while ((c = (char) stream.read()) != -1) {
            strHeaders.append(c);
            if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
                // end of headers
                break;
            }
        }

        // Match headers to get metadata offset within a stream
        Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
        Matcher m = p.matcher(strHeaders.toString());
        if (m.find()) {
            metaDataOffset = Integer.parseInt(m.group(2));
        }
    }

    // In case no data was sent
    if (metaDataOffset == 0) {
        isError = true;
        return;
    }

    // Read metadata
    int b;
    int count = 0;
    int metaDataLength = 4080; // 4080 is the max length
    boolean inData = false;
    StringBuilder metaData = new StringBuilder();
    // Stream position should be either at the beginning or right after headers
    while ((b = stream.read()) != -1) {
        count++;

        // Length of the metadata
        if (count == metaDataOffset + 1) {
            metaDataLength = b * 16;
        }

        if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
            inData = true;
        } else {
            inData = false;
        }
        if (inData) {
            if (b != 0) {
                metaData.append((char) b);
            }
        }
        if (count > (metaDataOffset + metaDataLength)) {
            break;
        }
    }

    // Set the data
    metadata = IcyStreamMeta.parseMetadata(metaData.toString());

    // Close
    stream.close();

}
 
开发者ID:bertrandmartel,项目名称:webradio-tv-app,代码行数:77,代码来源:IcyStreamMeta.java


注:本文中的java.net.URLConnection.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。