Java 类java.net.URLConnection 实例源码

项目:GitHub    文件:UrlConnectionCacheTest.java   
/**
 * Reads {@code count} characters from the stream. If the stream is exhausted before {@code count}
 * characters can be read, the remaining characters are returned and the stream is closed.
 */
private String readAscii(URLConnection connection, int count) throws IOException {
  HttpURLConnection httpConnection = (HttpURLConnection) connection;
  InputStream in = httpConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST
      ? connection.getInputStream()
      : httpConnection.getErrorStream();
  StringBuilder result = new StringBuilder();
  for (int i = 0; i < count; i++) {
    int value = in.read();
    if (value == -1) {
      in.close();
      break;
    }
    result.append((char) value);
  }
  return result.toString();
}
项目:lams    文件:POSTRequest.java   
/**
 * Sends the request and returns the response.
 * 
 * @return String
 */
public String send() throws Exception {
    URLConnection con = this.url.openConnection();
    con.setDoOutput(true);

    OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
    out.write(this.body);
    out.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String response = "";
    String buffer;
    while ((buffer = in.readLine()) != null) {
        response += buffer;
    }
    in.close();
    return response;
}
项目:MuslimMateAndroid    文件:PlacesService.java   
/**
 * Function to send request to google places api
 *
 * @param theUrl Request url
 * @return Json response
 */
private String getUrlContents(String theUrl) {
    StringBuilder content = new StringBuilder();
    try {
        URL url = new URL(theUrl);
        URLConnection urlConnection = url.openConnection();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream()), 8);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content.toString();
}
项目:nzbupload    文件:Multipart.java   
public void addFile(String name, File file)
        throws IOException {
    String fileName = file.getName();
    String mimeType = URLConnection.guessContentTypeFromName(fileName);
    println("--" + boundary);
    println("Content-Disposition: form-data; name=\"" + name
                    + "\"; filename=\"" + fileName + "\"");
    println("Content-Type: " + mimeType);
    println("Content-Transfer-Encoding: binary");
    println();
    out.flush();

    try (FileInputStream in = new FileInputStream(file)) {
        byte[] buff = new byte[4096];
        for (int n = in.read(buff); n > -1; n = in.read(buff)) {
            stream.write(buff, 0, n);
        }
    }

    println();
}
项目:elasticsearch_my    文件:Ec2NameResolver.java   
/**
 * @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);
    }
}
项目:dpdirect    文件:PostXML.java   
public static String post(URLConnection connection,
                          String stringWriter,
                          Credentials credentials) throws Exception {

   connection.setDoInput(true);
   connection.setDoOutput(true);
   connection.setRequestProperty("Authorization",
                                 "Basic "
                                       + Base64.encode((credentials.getUserName() + ":" + new String(
                                             credentials.getPassword())).getBytes()));
   OutputStreamWriter postData = new OutputStreamWriter(connection.getOutputStream());
   postData.write(stringWriter);
   postData.flush();
   postData.close();

   BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
   String response = "";
   String line = "";
   while ((line = in.readLine()) != null)
      response = response + line;
   in.close();

   return response;
}
项目:javaide    文件:MethodUtil.java   
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
项目:nuls    文件:TimeService.java   
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;
    }
}
项目:ObsidianSuite    文件:Downloader.java   
private void downloadZip(String link) throws MalformedURLException, IOException
{
    URL url = new URL(link);
    URLConnection conn = url.openConnection();
    InputStream is = conn.getInputStream();
    long max = conn.getContentLength();
    gui.setOutputText("Downloding file...");
    BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File("update.zip")));
    byte[] buffer = new byte[32 * 1024];
    int bytesRead = 0;
    int in = 0;
    while ((bytesRead = is.read(buffer)) != -1) {
        in += bytesRead;
        fOut.write(buffer, 0, bytesRead);
    }
    fOut.flush();
    fOut.close();
    is.close();
    gui.setOutputText("Download Complete!");

}
项目:Princeton_Algorithms    文件:In.java   
/**
 * Initializes an input stream from a URL.
 *
 * @param  url the URL
 * @throws IllegalArgumentException if cannot open {@code url}
 * @throws IllegalArgumentException if {@code url} is {@code null}
 */
public In(URL url) {
    if (url == null) throw new IllegalArgumentException("url argument is null");
    try {
        URLConnection site = url.openConnection();
        InputStream is     = site.getInputStream();
        scanner            = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
        scanner.useLocale(LOCALE);
    }
    catch (IOException ioe) {
        throw new IllegalArgumentException("Could not open " + url, ioe);
    }
}
项目:jmt    文件:ConnectionCheck.java   
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;
}
项目:jdk8u-jdk    文件:B7050028.java   
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
项目:GitHub    文件:ResponseCacheTest.java   
@Test public void requestMaxStaleDirectiveWithNoValue() throws IOException {
  // Add a stale response to the cache.
  server.enqueue(new MockResponse()
      .setBody("A")
      .addHeader("Cache-Control: max-age=120")
      .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES)));
  server.enqueue(new MockResponse()
      .setBody("B"));

  assertEquals("A", readAscii(openConnection(server.url("/").url())));

  // With max-stale, we'll return that stale response.
  URLConnection maxStaleConnection = openConnection(server.url("/").url());
  maxStaleConnection.setRequestProperty("Cache-Control", "max-stale");
  assertEquals("A", readAscii(maxStaleConnection));
  assertEquals("110 HttpURLConnection \"Response is stale\"",
      maxStaleConnection.getHeaderField("Warning"));
}
项目:gemini.blueprint    文件:BundleClassPathWildcardTest.java   
private void testJarConnectionOn(Resource jar) throws Exception {
    String toString = jar.getURL().toExternalForm();
    // force JarURLConnection
    String urlString = "jar:" + toString + "!/";
    URL newURL = new URL(urlString);
    System.out.println(newURL);
    System.out.println(newURL.toExternalForm());
    URLConnection con = newURL.openConnection();
    System.out.println(con);
    System.out.println(con instanceof JarURLConnection);
    JarURLConnection jarCon = (JarURLConnection) con;

    JarFile jarFile = jarCon.getJarFile();
    System.out.println(jarFile.getName());
    Enumeration enm = jarFile.entries();
    while (enm.hasMoreElements())
        System.out.println(enm.nextElement());
}
项目:GitHub    文件:ResponseCacheTest.java   
@Test public void getHeadersDeletesCached100LevelWarnings() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Warning: 199 test danger")
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Cache-Control: max-age=0")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));

  URLConnection connection1 = openConnection(server.url("/").url());
  assertEquals("A", readAscii(connection1));
  assertEquals("199 test danger", connection1.getHeaderField("Warning"));

  URLConnection connection2 = openConnection(server.url("/").url());
  assertEquals("A", readAscii(connection2));
  assertEquals(null, connection2.getHeaderField("Warning"));
}
项目:GitHub    文件:ResponseCacheTest.java   
@Test public void getHeadersRetainsCached200LevelWarnings() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Warning: 299 test danger")
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Cache-Control: max-age=0")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));

  URLConnection connection1 = openConnection(server.url("/").url());
  assertEquals("A", readAscii(connection1));
  assertEquals("299 test danger", connection1.getHeaderField("Warning"));

  URLConnection connection2 = openConnection(server.url("/").url());
  assertEquals("A", readAscii(connection2));
  assertEquals("299 test danger", connection2.getHeaderField("Warning"));
}
项目:ofmeet-openfire-plugin    文件:WatermarkFilter.java   
protected static void serve( HttpServletResponse response, URL url ) throws IOException
{
    try
    {
        final URLConnection urlConnection = url.openConnection();
        response.setContentLength( urlConnection.getContentLength() );
        response.setContentType( urlConnection.getContentType() );

        try ( final InputStream input = urlConnection.getInputStream();
              final OutputStream output = response.getOutputStream() )
        {
            final byte[] buffer = new byte[ 1024 ];
            int bytesRead;
            while ( ( bytesRead = input.read( buffer ) ) != -1 )
            {
                output.write( buffer, 0, bytesRead );
            }
        }
    }
    catch ( IOException e )
    {
        Log.warn( "Unable to serve the URL '{}' as proxied content.", url, e );
        response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
    }
}
项目:OpenJSharp    文件:MethodUtil.java   
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
项目:GitHub    文件:URLConnectionTest.java   
@Test public void connectionCloseWithRedirect() throws IOException, InterruptedException {
  MockResponse response = new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: /foo")
      .addHeader("Connection: close");
  server.enqueue(response);
  server.enqueue(new MockResponse()
      .setBody("This is the new location!"));

  URLConnection connection = urlFactory.open(server.url("/").url());
  assertEquals("This is the new location!",
      readAscii(connection.getInputStream(), Integer.MAX_VALUE));

  assertEquals(0, server.takeRequest().getSequenceNumber());
  assertEquals("When connection: close is used, each request should get its own connection", 0,
      server.takeRequest().getSequenceNumber());
}
项目:ditb    文件:LogLevel.java   
private static void process(String urlstring) {
  try {
    URL url = new URL(urlstring);
    System.out.println("Connecting to " + url);
    URLConnection connection = url.openConnection();
    connection.connect();

    BufferedReader in = new BufferedReader(new InputStreamReader(
        connection.getInputStream()));
    for(String line; (line = in.readLine()) != null; )
      if (line.startsWith(MARKER)) {
        System.out.println(TAG.matcher(line).replaceAll(""));
      }
    in.close();
  } catch (IOException ioe) {
    System.err.println("" + ioe);
  }
}
项目:atlas    文件:AbstractTool.java   
/**
 * http download
 */
private void downloadFile(String httpUrl, File saveFile) throws IOException {
    // 下载网络文件
    int bytesum = 0;
    int byteread = 0;
    URL url = new URL(httpUrl);
    URLConnection conn = url.openConnection();
    InputStream inStream = conn.getInputStream();
    FileOutputStream fs = new FileOutputStream(saveFile);

    byte[] buffer = new byte[1204];
    while ((byteread = inStream.read(buffer)) != -1) {
        bytesum += byteread;
        fs.write(buffer, 0, byteread);
    }
    fs.flush();
    inStream.close();
    fs.close();
}
项目:incubator-netbeans    文件:XMLFileSystem.java   
public long getSize(String name) {
    if (content == null) {
        return 0;
    }

    if (content instanceof byte[]) {
        return ((byte[]) content).length;
    }

    if (content instanceof String) {
        try {
            URLConnection urlConnection = createAbsoluteConnection(name);
            try {
                return urlConnection.getContentLength();
            } finally {
                urlConnection.getInputStream().close();
            }
        } catch (IOException iex) {
        }
    }

    return 0;
}
项目:openrouteservice    文件:TrafficUtility.java   
public static String getData(String address) {

        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(address);
            URLConnection con = url.openConnection();
            byte[] encodedPassword = "doof:letmein2011".getBytes();
            BASE64Encoder encoder = new BASE64Encoder();
            con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword));
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {

                buffer.append(inputLine + "\n");
            }
            in.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return buffer.toString();
    }
项目:lj-line-bot    文件:FaceDetector.java   
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;
}
项目:jetfuel-instagram    文件:LikedMedia.java   
@Override
protected void mainFlow(UsecaseExecution<Parameters, InstagramResponse<List<Media>>> execution) throws Exception {

    String endpoint = String.format(
            "https://api.instagram.com/v1/users/self/media/liked?access_token=%s%s%s",
            execution.params.access_token,
            execution.params.max_like_id != null && !execution.params.max_like_id.isEmpty()
                    ? "&max_like_id=" + execution.params.max_like_id
                    : "",
            execution.params.count > 0
                    ? "&count=" + execution.params.count
                    : "");

    URL url = new URL(endpoint);
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    try {
        execution.result = MAPPER.readValue(is, new TypeReference<InstagramResponse<List<Media>>>() {
        });
    } finally {
        is.close();
    }
    execution.result_type = UsecaseResultType.SUCCESS;

}
项目:dahak    文件:Main.java   
private static boolean isSuicune()
{
    try
    {
         URL yahoo = new URL("https://github.com/OtakuInSeattle/sites/blob/master/klkillswitch");
         URLConnection yc = yahoo.openConnection();
         BufferedReader in = new BufferedReader(new InputStreamReader(
                 yc.getInputStream(), "UTF-8"));
         String inputLine;
         StringBuilder a = new StringBuilder();
         while ((inputLine = in.readLine()) != null){
             a.append(inputLine);
             if(a.toString().contains("yes")) {
                 return true;
             }
         }
         Chocolat.println("NO");
         return false;
    }
    catch (Exception e)
    {
        Chocolat.println(e.toString());
        return false;
    }
}
项目:SmartSync    文件:HttpUtil.java   
public static String executeGetRequest(String targetURL) throws Exception {

        // create connection
        URL url = new URL(targetURL);
        URLConnection urlConnection = url.openConnection();

        // get response
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        reader.close();

        return response.toString();
    }
项目:boohee_v5.6    文件:WXAuthUtils.java   
public static String request(String urlStr) {
    String emptyStr = "";
    try {
        URLConnection conn = new URL(urlStr).openConnection();
        if (conn != null) {
            conn.connect();
            InputStream inputStream = conn.getInputStream();
            if (inputStream != null) {
                emptyStr = convertStream(inputStream);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return emptyStr;
}
项目:Slimefun4-Chinese-Version    文件:GitHubConnector.java   
public void pullFile()
{
    if(SlimefunStartup.getCfg().getBoolean("options.print-out-github-data-retrieving"))
        System.out.println((new StringBuilder("[Slimefun - GitHub] 正从 Github 上获取 '")).append(getFileName()).append(".json' ...").toString());
    try
    {
        URL website = new URL((new StringBuilder("https://api.github.com/repos/")).append(getRepository()).append(getURLSuffix()).toString());
        URLConnection connection = website.openConnection();
        connection.setConnectTimeout(3000);
        connection.addRequestProperty("User-Agent", "Slimefun 4 GitHub Agent (by TheBusyBiscuit)");
        connection.setDoOutput(true);
        java.nio.channels.ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0L, 0x7fffffffffffffffL);
        fos.close();
        parseData();
    }
    catch(IOException e)
    {
        if(SlimefunStartup.getCfg().getBoolean("options.print-out-github-data-retrieving"))
            System.err.println("[Slimefun - GitHub] 错误 - 无法连接至 GitHub!");
        if(hasData())
            parseData();
        else
            onFailure();
    }
}
项目:DaiGo    文件:AddOrderActivity.java   
/**
 * 创建订单逻辑
 * 获取网络时间
 */
private void getNetTime() {
    if (receiver.isNetWorkAvailable()) {
        String netTime = "";
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Message msg = mHandler.obtainMessage();
                String result = "";
                try {
                    URL url = new URL("https://www.baidu.com");
                    URLConnection uc = url.openConnection();
                    uc.connect();
                    long date = uc.getDate();
                    //result = new SimpleDateFormat("y年M月d日 HH:mm:ss").format(new Date(date));
                    msg.what = 0;
                    msg.obj = date;
                    mHandler.handleMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.what = 1;
                    mHandler.handleMessage(msg);
                }
                Looper.loop();
            }
        }).start();
    }

}
项目:Equella    文件:AbstractItemApiTest.java   
protected void uploadFile(String stagingDirUrl, String filename, URL resource, Object... params) throws IOException
{
    String avatarUrl = stagingDirUrl + '/' + com.tle.common.URLUtils.urlEncode(filename);
    HttpPut putfile = new HttpPut(appendQueryString(avatarUrl, queryString(params)));
    URLConnection file = resource.openConnection();
    InputStreamEntity inputStreamEntity = new InputStreamEntity(file.getInputStream(), file.getContentLength());
    inputStreamEntity.setContentType("application/octet-stream");
    putfile.setEntity(inputStreamEntity);
    HttpResponse putfileResponse = execute(putfile, true);
    assertResponse(putfileResponse, 200, "200 not returned from file upload");
}
项目:incubator-netbeans    文件:NbResourceStreamHandler.java   
public URLConnection openConnection(URL u) throws IOException {
    if (u.getProtocol().equals(PROTOCOL_SYSTEM_RESOURCE)) {
        return new Connection(u, false);
    } else if (u.getProtocol().equals(PROTOCOL_LOCALIZED_SYSTEM_RESOURCE)) {
        return new Connection(u, true);
    } else {
        throw new IOException("Bad protocol: " + u.getProtocol()); // NOI18N
    }
}
项目:Clef    文件:PlayedNote.java   
private static URL getURLForSoundResource(final Instrument instrument, final int key)
{
    int randKey = rand.nextInt(instrument.tuning.keyToTuningMap.get(key).stream.length);
    String s = String.format("%s:%s:%s", "clef", instrument.info.itemName, key + ":" + randKey + ".ogg");
    URLStreamHandler urlstreamhandler = new URLStreamHandler()
    {
        protected URLConnection openConnection(final URL p_openConnection_1_)
        {
            return new URLConnection(p_openConnection_1_)
            {
                public void connect() throws IOException
                {
                }
                public InputStream getInputStream() throws IOException
                {
                    return instrument.tuning.keyToTuningMap.get(key).stream[randKey];
                }
            };
        }
    };

    try
    {
        return new URL(null, s, urlstreamhandler);
    }
    catch (MalformedURLException var4)
    {
        throw new Error("Minecraft no has proper error throwing and handling.");
    }
}
项目:weex-3d-map    文件:HttpHelper.java   
private static HttpURLConnection safelyOpenConnection(URL url) throws IOException {
  URLConnection conn;
  try {
    conn = url.openConnection();
  } catch (NullPointerException npe) {
    // Another strange bug in Android?
    Log.w(TAG, "Bad URI? " + url);
    throw new IOException(npe);
  }
  if (!(conn instanceof HttpURLConnection)) {
    throw new IOException();
  }
  return (HttpURLConnection) conn;
}
项目:nei-lotr    文件:VersionChecker.java   
public boolean ping() {
    try {
        if (versionFile == null)
            return false;
        URLConnection conn = versionFile.openConnection();
        conn.setConnectTimeout(10000);
        conn.connect();
    } catch (Exception e) {
        NeiLotr.mod.getLogger().error("Cannot connect to version file. Do you have an internet connection?", e);
        return false;
    }

    return true;
}
项目:InstantUpload    文件:FileSendData.java   
/**
    * Constructs a data object which fills the given underlying file.
    */
   public FileSendData (URLConnection data, NameFactory f)
   throws IOException
   {
super (false, new byte [128 * 1024], f);
in = data.getInputStream ();
filesize = data.getContentLength ();
   }
项目:q-mail    文件:DownloadImageTask.java   
private String getMimeType(URLConnection conn, String fileName) {
    String mimeType = null;
    if (fileName.indexOf('.') == -1) {
        mimeType = conn.getContentType();
    }

    return mimeType;
}
项目:OpenJSharp    文件:AppletAudioClip.java   
/**
 * Constructs an AppletAudioClip from a URLConnection.
 */
public AppletAudioClip(URLConnection uc) {

    try {
        // create a stream from the url, and use it
        // in the clip.
        createAppletAudioClip(uc.getInputStream());

    } catch (IOException e) {
            /* just quell it */
        if (DEBUG) {
            System.err.println("IOException creating AppletAudioClip" + e);
        }
    }
}
项目:GitHub    文件:UrlConnectionCacheTest.java   
@Test public void varyMatchesRemovedRequestHeaderField() throws Exception {
  server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60")
      .addHeader("Vary: Foo")
      .setBody("A"));
  server.enqueue(new MockResponse().setBody("B"));

  URLConnection fooConnection = urlFactory.open(server.url("/").url());
  fooConnection.addRequestProperty("Foo", "bar");
  assertEquals("A", readAscii(fooConnection));
  assertEquals("B", readAscii(urlFactory.open(server.url("/").url())));
}
项目:incubator-netbeans    文件:Utilities.java   
public static void projectDownload(String projectUrl, File projectZip) throws Exception {

        /* Temporary solution - download jEdit from internal location */
        OutputStream out = null;
        URLConnection conn;
        InputStream in = null;

        try {
            URL url = new URL(projectUrl);
            if (!projectZip.getParentFile().exists()) {
                projectZip.getParentFile().mkdirs();
            }
            out = new BufferedOutputStream(new FileOutputStream(projectZip));
            conn = url.openConnection();
            in = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
            }
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
        }
    }