本文整理汇总了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();
}
示例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();
}
}
示例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;
}
}
示例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;
}
示例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
}
示例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();
}
}
);
}
示例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);
}
}
示例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;
}
示例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;
}
示例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();
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例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;
}