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


Java URL類代碼示例

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


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

示例1: testAddAndSetRequestPropertyWithSameKey

import java.net.URL; //導入依賴的package包/類
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testAddAndSetRequestPropertyWithSameKey() throws Exception {
    URL url = new URL(NativeTestServer.getEchoAllHeadersURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.addRequestProperty("header-name", "value1");
    connection.setRequestProperty("Header-nAme", "value2");

    // Before connection is made, check request headers are set.
    assertEquals("value2", connection.getRequestProperty("header-namE"));
    Map<String, List<String>> requestHeadersMap =
            connection.getRequestProperties();
    assertEquals(1, requestHeadersMap.get("HeAder-name").size());
    assertEquals("value2", requestHeadersMap.get("HeAder-name").get(0));

    // Check the request headers echoed back by the server.
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    String headers = TestUtil.getResponseAsString(connection);
    List<String> actualValues =
            getRequestHeaderValues(headers, "Header-nAme");
    assertEquals(1, actualValues.size());
    assertEquals("value2", actualValues.get(0));
    connection.disconnect();
}
 
開發者ID:lizhangqu,項目名稱:chromium-net-for-android,代碼行數:27,代碼來源:CronetHttpURLConnectionTest.java

示例2: getResponseFromHttpUrl

import java.net.URL; //導入依賴的package包/類
/**
 * This method returns the entire result from the HTTP response.
 *
 * @param url The URL to fetch the HTTP response from.
 * @return The contents of the HTTP response, null if no response
 * @throws IOException Related to network and stream reading
 */
public static String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");

        boolean hasInput = scanner.hasNext();
        String response = null;
        if (hasInput) {
            response = scanner.next();
        }
        scanner.close();
        return response;
    } finally {
        urlConnection.disconnect();
    }
}
 
開發者ID:fjoglar,項目名稱:android-dev-challenge,代碼行數:27,代碼來源:NetworkUtils.java

示例3: getImage

import java.net.URL; //導入依賴的package包/類
public synchronized Image getImage(URL url) {
    Object o = imageCache.get(url);
    if (o != null) {
        return (Image)o;
    }
    try {
        o = url.getContent();
        if (o == null) {
            return null;
        }
        if (o instanceof Image) {
            imageCache.put(url, o);
            return (Image) o;
        }
        // Otherwise it must be an ImageProducer.
        Image img = target.createImage((java.awt.image.ImageProducer)o);
        imageCache.put(url, img);
        return img;

    } catch (Exception ex) {
        return null;
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:24,代碼來源:Beans.java

示例4: load

import java.net.URL; //導入依賴的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

示例5: getRegisteredMavenRepositories

import java.net.URL; //導入依賴的package包/類
@NotNull
@Override
public List<URL> getRegisteredMavenRepositories() {
    if(registeredMavenRepositories == null || registeredMavenRepositories.get() == null) {
        registeredMavenRepositories = new SoftReference<>(Collections.unmodifiableList(
                orionCore.modMavenRepositories.stream().map(u -> {
                    try {
                        return u.toURL();
                    } catch (MalformedURLException e) {
                        SneakyThrow.throwException(e);
                        return null;
                    }
                })
                .collect(Collectors.toList())
        ));
    }

    return Objects.requireNonNull(registeredMavenRepositories.get()); // Should not throw NPE
}
 
開發者ID:OrionMinecraft,項目名稱:Orion,代碼行數:20,代碼來源:OrionAPIImpl.java

示例6: fetchLoginUrl

import java.net.URL; //導入依賴的package包/類
/**
 * Retrieve the URL of the page that contains the login form
 */
private void fetchLoginUrl() {
    Log.d(TAG, "fetching login URL...");
    mRequestFactory.get(
            "https://stackexchange.com/users/signin",
            true,
            new RequestListener() {
                @Override
                public void onSucceeded(URL url, String data) {
                    mListener.authProgress(20);
                    mLoginUrl = data;
                    fetchNetworkFkey();
                }
            }
    );
}
 
開發者ID:HueToYou,項目名稱:ChatExchange-old,代碼行數:19,代碼來源:StackExchangeAuth.java

示例7: businessFrom

import java.net.URL; //導入依賴的package包/類
static Business businessFrom(JSONObject information) {
    try {
        return new Business(
            information.getDouble("rating"),
            information.has("price") ? PricingLevel.fromSymbol(information.getString("price")) : PricingLevel.NONE,
            information.getString("phone"),
            information.getString("id"),
            information.getBoolean("is_closed"),
            buildCategories(information.getJSONArray("categories")),
            information.getInt("review_count"),
            information.getString("name"),
            new URL(information.getString("url")),
            CoordinatesParser.from(information.getJSONObject("coordinates")),
            !information.getString("image_url").trim().isEmpty() ? new URL(information.getString("image_url")) : null,
            LocationParser.from(information.getJSONObject("location")),
            !information.isNull("distance") ? Distance.inMeters(information.getDouble("distance")) : null,
            buildTransactions(information.getJSONArray("transactions"))
        );
    } catch (JSONException | MalformedURLException exception) {
        throw ParsingFailure.producedBy(information, exception);
    }
}
 
開發者ID:MontealegreLuis,項目名稱:yelpv3-java-client,代碼行數:23,代碼來源:BusinessParser.java

示例8: doInBackground

import java.net.URL; //導入依賴的package包/類
@Override
protected EpubPublication doInBackground(String... urls) {
    String strUrl = urls[0];

    try {
        URL url = new URL(strUrl);
        URLConnection urlConnection = url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        Log.d("TestActivity", "EpubPublication => " + stringBuilder.toString());

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        return objectMapper.readValue(stringBuilder.toString(), EpubPublication.class);
    } catch (IOException e) {
        Log.e(TAG, "SpineListTask error " + e);
    }
    return null;
}
 
開發者ID:codetoart,項目名稱:r2-streamer-java,代碼行數:27,代碼來源:TestActivity.java

示例9: listStatus

import java.net.URL; //導入依賴的package包/類
/**
 * <b>LISTSTATUS</b>
 *
 * curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=LISTSTATUS"
 *
 * @param path
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String listStatus(String path) throws MalformedURLException,
        IOException, AuthenticationException {
    ensureValidToken();
    System.out.println("Token = "+token.isSet());

    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl), MessageFormat.format(
                    "/webhdfs/v1/{0}?op=LISTSTATUS",
                    URLUtil.encodePath(path))), token);
    conn.setRequestMethod("GET");
    conn.connect();
    String resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
開發者ID:Transwarp-DE,項目名稱:Transwarp-Sample-Code,代碼行數:28,代碼來源:KerberosWebHDFSConnection2.java

示例10: scanJar

import java.net.URL; //導入依賴的package包/類
protected void scanJar(URL jarUrl, Map<String, ResourceInfo> resInfos) throws IOException {
  JarInputStream jarInput = new JarInputStream(jarUrl.openStream(), false);
  JarEntry entry = null;
  while((entry = jarInput.getNextJarEntry()) != null) {
    String entryName = entry.getName();
    if(entryName != null && entryName.endsWith(".class")) {
      final String className = entryName.substring(0,
               entryName.length() - 6).replace('/', '.');
      if(!resInfos.containsKey(className)) {
        ClassReader classReader = new ClassReader(jarInput);
        ResourceInfo resInfo = new ResourceInfo(null, className, null);
        ResourceInfoVisitor visitor = new ResourceInfoVisitor(resInfo);

        classReader.accept(visitor, ClassReader.SKIP_CODE |
            ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
        if(visitor.isCreoleResource()) {
          resInfos.put(className, resInfo);
        }
      }
    }
  }

  jarInput.close();
}
 
開發者ID:GateNLP,項目名稱:gate-core,代碼行數:25,代碼來源:Plugin.java

示例11: getLargestImagePageDocument

import java.net.URL; //導入依賴的package包/類
private Document getLargestImagePageDocument(URL url) throws IOException {
    // Get current page
    Document doc = Http.url(url).get();
    // Look for larger image page
    String largestImagePage = this.url.toExternalForm();
    for (Element olSize : doc.select("ol.sizes-list > li > ol > li")) {
        Elements ola = olSize.select("a");
        if (ola.size() == 0) {
            largestImagePage = this.url.toExternalForm();
        }
        else {
            String candImage = ola.get(0).attr("href");
            if (candImage.startsWith("/")) {
                candImage = "http://www.flickr.com" + candImage;
            }
            largestImagePage = candImage;
        }
    }
    if (!largestImagePage.equals(this.url.toExternalForm())) {
        // Found larger image page, get it.
        doc = Http.url(largestImagePage).get();
    }
    return doc;
}
 
開發者ID:RipMeApp,項目名稱:ripme,代碼行數:25,代碼來源:FlickrRipper.java

示例12: fetchImage

import java.net.URL; //導入依賴的package包/類
/**
 * Download the most recent fsimage from the name node, and save it to a local
 * file in the given directory.
 * 
 * @param argv
 *          List of of command line parameters.
 * @param idx
 *          The index of the command that is being processed.
 * @return an exit code indicating success or failure.
 * @throws IOException
 */
public int fetchImage(final String[] argv, final int idx) throws IOException {
  Configuration conf = getConf();
  final URL infoServer = DFSUtil.getInfoServer(
      HAUtil.getAddressOfActive(getDFS()), conf,
      DFSUtil.getHttpClientScheme(conf)).toURL();
  SecurityUtil.doAsCurrentUser(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      TransferFsImage.downloadMostRecentImageToDirectory(infoServer,
          new File(argv[idx]));
      return null;
    }
  });
  return 0;
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:27,代碼來源:DFSAdmin.java

示例13: getDocEncoding

import java.net.URL; //導入依賴的package包/類
private String getDocEncoding(URL root) {
    assert root != null && root.toString().endsWith("/") : root;
    InputStream is = URLUtils.open(root, "index-all.html", "index-files/index-1.html");
    if (is != null) {
        try {
            try {
                ParserDelegator pd = new ParserDelegator();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                EncodingCallback ecb = new EncodingCallback(in);
                pd.parse(in, ecb, true);
                return ecb.getEncoding();
            } finally {
                is.close();
            }
        } catch (IOException x) {
            LOG.log(Level.FINE, "Getting encoding from " + root, x);
        }
    }
    return null;
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:21,代碼來源:JavadocRegistry.java

示例14: proxyWithConnectionClose

import java.net.URL; //導入依賴的package包/類
@Test public void proxyWithConnectionClose() throws IOException {
  server.useHttps(sslClient.socketFactory, true);
  server.enqueue(
      new MockResponse().setSocketPolicy(UPGRADE_TO_SSL_AT_END).clearHeaders());
  server.enqueue(new MockResponse().setBody("this response comes via a proxy"));

  urlFactory.setClient(urlFactory.client().newBuilder()
      .proxy(server.toProxyAddress())
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(new RecordingHostnameVerifier())
      .build());

  URL url = new URL("https://android.com/foo");
  connection = urlFactory.open(url);
  connection.setRequestProperty("Connection", "close");

  assertContent("this response comes via a proxy", connection);
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:19,代碼來源:URLConnectionTest.java

示例15: doInBackground

import java.net.URL; //導入依賴的package包/類
@Override
protected Void doInBackground(Integer... params) {
    for (Integer cur : params) {
        remote = cur;
        try {
            URLConnection connection =
                    new URL(Utils.BASE_URL_PHP + "updateViewTracker.php?remote=" + remote)
                            .openConnection();

            connection.getInputStream();
            Utils.getController().getPreferences()
                    .edit()
                    .putString("pref_key_cache_vieweditems", getNewCacheString())
                    .apply();
        } catch (IOException e) {
            Utils.logError(e);
        }
    }
    return null;
}
 
開發者ID:LCA311,項目名稱:leoapp-sources,代碼行數:21,代碼來源:UpdateViewTrackerTask.java


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