下面列出了怎么用java.net.URLConnection的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Connect, retrying if needed.
*
* @return The connection.
*/
public URLConnection connect() throws IOException {
if (url == null) {
throw new IllegalStateException("url is required");
}
Log.debug("connecting to %s, headers=%s", url, headers);
IOException lastCaught = null;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
URLConnection result = connector.connect(url, headers, connectTimeout, readTimeout);
Log.debug("connected to %s, headers=%s", url, result.getHeaderFields());
return result;
} catch (UnknownHostException | SocketException | SocketTimeoutException e) {
lastCaught = e;
delay.execute(attempt, maxAttempts);
}
}
throw requireNonNull(lastCaught);
}
private String guessMimeType(String path)
{
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = null;
try
{
contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8"));
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if (contentTypeFor == null)
{
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
}
/**
* Get the class of the scriptName in question, so that you can instantiate
* Groovy objects with caching and reloading.
*
* @param scriptName resource name pointing to the script
* @return the loaded scriptName as a compiled class
* @throws ResourceException if there is a problem accessing the script
* @throws ScriptException if there is a problem parsing the script
*/
public Class loadScriptByName(String scriptName) throws ResourceException, ScriptException {
URLConnection conn = rc.getResourceConnection(scriptName);
String path = conn.getURL().toExternalForm();
ScriptCacheEntry entry = scriptCache.get(path);
Class clazz = null;
if (entry != null) clazz = entry.scriptClass;
try {
if (isSourceNewer(entry)) {
try {
String encoding = conn.getContentEncoding() != null ? conn.getContentEncoding() : config.getSourceEncoding();
String content = IOGroovyMethods.getText(conn.getInputStream(), encoding);
clazz = groovyLoader.parseClass(content, path);
} catch (IOException e) {
throw new ResourceException(e);
}
}
} finally {
forceClose(conn);
}
return clazz;
}
@Override
protected URLConnection openConnection(final URL u) throws IOException {
if (!u.getFile().endsWith("SmallRyeConfigFactory")) {
return null;
}
return new URLConnection(u) {
@Override
public void connect() throws IOException {
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(contents);
}
};
}
@Override
protected URLConnection openConnection(final URL u) throws IOException
{
String externalForm = u.toExternalForm();
if(externalForm.startsWith("classpath:"))
{
String path = externalForm.substring(10);
URL resourceUrl = getClass().getClassLoader().getResource(path);
if(resourceUrl == null)
{
throw new FileNotFoundException("No such resource found in the classpath: " + path);
}
return resourceUrl.openConnection();
}
else
{
throw new MalformedURLException("'"+externalForm+"' does not start with 'classpath:'");
}
}
/**
* 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();
}
@Override
public void run() {
//访问特定的dispatcher地址
long startTime = System.currentTimeMillis();
try {
URL url = new URL(targetUrl);
URLConnection httpURLConnection = url.openConnection();
httpURLConnection.setUseCaches(false);
httpURLConnection.connect();
Object o = httpURLConnection.getContent();
long cost = (System.currentTimeMillis()-startTime);
if (cost > 100)
{
logger.debug(o + " cost:"+cost+"ms");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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()));
}
public static void download(String urlString) throws Exception {
File file = new File(urlString);
String filename = file.getName();
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
OutputStream os = new FileOutputStream(filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
@Override
public InputStream openStream(String url, Map<String, String> headers, int connectTimeout, int readTimeout)
throws IOException {
URLConnection connection = openConnection(url, headers, connectTimeout, readTimeout);
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConnection = HttpsURLConnection.class.cast(connection);
//httpsConnection.setHostnameVerifier(InsecureStreamProvider.INSECURE_HOSTNAME_VERIFIER);
httpsConnection.setSSLSocketFactory(getSSLSocketFactory());
if (log.isLoggable(Level.FINE)) {
log.fine(String.format("Using HttpsURLConnection with SSLSocketFactory [%s] for url [%s].", factory, url));
}
} else {
if (log.isLoggable(Level.FINE)) {
log.fine(String.format("Using URLConnection for url [%s].", url));
}
}
if (token != null) {
// curl -k -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" \
// https://172.30.0.2:443/api/v1/namespaces/dward/pods?labelSelector=application%3Deap-app
headers.put("Authorization", "Bearer " + token);
}
return connection.getInputStream();
}
/**
* Downloads a file from specified url.
*
* @param url the url to download
* @param output the output location
* @param progress the progress tracker to show download progress
* @throws IOException when IO operation fails in downloading
*/
public static void download(URL url, Path output, Progress progress) throws IOException {
if (Files.exists(output)) {
return;
}
Path dir = output.toAbsolutePath().getParent();
if (dir != null) {
Files.createDirectories(dir);
}
URLConnection conn = url.openConnection();
if (progress != null) {
long contentLength = conn.getContentLengthLong();
if (contentLength > 0) {
progress.reset("Downloading", contentLength, output.toFile().getName());
}
}
try (InputStream is = conn.getInputStream()) {
ProgressInputStream pis = new ProgressInputStream(is, progress);
String fileName = url.getFile();
if (fileName.endsWith(".gz")) {
Files.copy(new GZIPInputStream(pis), output);
} else {
Files.copy(pis, output);
}
}
}
@Override
protected void onNextClicked(File savedPDFFile) {
Intent intentShareFile = new Intent(Intent.ACTION_SEND);
Uri apkURI = FileProvider.getUriForFile(
getApplicationContext(),
getApplicationContext()
.getPackageName() + ".provider", savedPDFFile);
intentShareFile.setDataAndType(apkURI, URLConnection.guessContentTypeFromName(savedPDFFile.getName()));
intentShareFile.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intentShareFile.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + savedPDFFile.getAbsolutePath()));
startActivity(Intent.createChooser(intentShareFile, "Share File"));
}
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()));
}
/**
* Asserts that the content of a file is the same as expected. Checks the length reported by getContentLength() is
* correct, then reads the content as a byte stream and compares the result with the expected content. Assumes files
* are encoded using UTF-8.
*/
protected void assertSameURLContent(final String expected, final URLConnection connection) throws Exception {
// Get file content as a binary stream
final byte[] expectedBin = expected.getBytes("utf-8");
// Check lengths
assertEquals("same content length", expectedBin.length, connection.getContentLength());
// Read content into byte array
final InputStream instr = connection.getInputStream();
final ByteArrayOutputStream outstr;
try {
outstr = new ByteArrayOutputStream();
final byte[] buffer = new byte[256];
int nread = 0;
while (nread >= 0) {
outstr.write(buffer, 0, nread);
nread = instr.read(buffer);
}
} finally {
instr.close();
}
// Compare
assertArrayEquals("same binary content", expectedBin, outstr.toByteArray());
}
public static String getPlayerName(UUID uuid){
if (Bukkit.isPrimaryThread()){
throw new RuntimeException("Requesting player UUID is not allowed on the primary thread!");
}
try {
URL url = new URL("https://api.mojang.com/user/profiles/"+uuid.toString().replace("-", "")+"/names");
URLConnection request = url.openConnection();
request.connect();
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonArray names = root.getAsJsonArray();
return names.get(names.size()-1).getAsJsonObject().get("name").getAsString();
}catch (IOException ex){
ex.printStackTrace();
return null;
}
}
/**
* Load all properties from the specified class path resource
* (in ISO-8859-1 encoding), using the given class loader.
* <p>Merges properties if more than one resource of the same name
* found in the class path.
* @param resourceName the name of the class path resource
* @param classLoader the ClassLoader to use for loading
* (or {@code null} to use the default class loader)
* @return the populated Properties instance
* @throws IOException if loading failed
*/
public static Properties loadAllProperties(String resourceName, ClassLoader classLoader) throws IOException {
Assert.notNull(resourceName, "Resource name must not be null");
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = ClassUtils.getDefaultClassLoader();
}
Enumeration<URL> urls = (classLoaderToUse != null ? classLoaderToUse.getResources(resourceName) :
ClassLoader.getSystemResources(resourceName));
Properties props = new Properties();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
URLConnection con = url.openConnection();
ResourceUtils.useCachesIfNecessary(con);
InputStream is = con.getInputStream();
try {
if (resourceName != null && resourceName.endsWith(XML_FILE_EXTENSION)) {
props.loadFromXML(is);
}
else {
props.load(is);
}
}
finally {
is.close();
}
}
return props;
}
/**
* Read in the content from a URL
* @param url URL To read
* @return the text from the output
* @throws IOException if something went wrong
*/
private static String readOutput(URL url) throws IOException {
StringBuilder out = new StringBuilder();
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream(), Charsets.UTF_8));
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.append(inputLine);
}
in.close();
return out.toString();
}
private URL replaceKnownRealmsByTomEEOnes(final URL contextXml) throws MalformedURLException {
return new URL(contextXml.getProtocol(), contextXml.getHost(), contextXml.getPort(), contextXml.getFile(), new URLStreamHandler() {
@Override
protected URLConnection openConnection(final URL u) throws IOException {
final URLConnection c = contextXml.openConnection();
return new URLConnection(u) {
@Override
public void connect() throws IOException {
c.connect();
}
@Override
public InputStream getInputStream() throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
IO.copy(c.getInputStream(), baos);
return new ByteArrayInputStream(new String(baos.toByteArray())
.replace(DataSourceRealm.class.getName(), TomEEDataSourceRealm.class.getName()
).getBytes());
}
@Override
public String toString() {
return c.toString();
}
};
}
});
}
public URLValidator(URI uri, URLConnection urlConnection,
long request_time, UrlConnectionExpiryCalculator
urlConnectionExpiryCalculator) {
this.uri = uri;
this.lastModified = urlConnection.getLastModified();
this.entityTags = getEntityTags(urlConnection);
expiry = calculateExpiry(urlConnection, request_time,
urlConnectionExpiryCalculator);
}
private static String consume(URLConnection connection) throws IOException {
String encoding = getEncoding(connection);
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
try {
in = connection.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
} finally {
try {
in.close();
} catch (IOException ioe) {
// continue
}
}
try {
return new String(out.toByteArray(), encoding);
} catch (UnsupportedEncodingException uee) {
try {
return new String(out.toByteArray(), "UTF-8");
} catch (UnsupportedEncodingException uee2) {
// can't happen
throw new IllegalStateException(uee2);
}
}
}
/**
* Disables caching for JAR URL connections. For Java 8 and earlier, this also disables
* caching for ALL URL connections.
*
* @throws IOException If a dummy JAR URLConnection can not be created
*/
public void disableCachingForJarUrlConnections() throws IOException {
// Doesn't matter that this JAR doesn't exist - just as
// long as the URL is well-formed
URL url = new URL("jar:file://dummy.jar!/");
URLConnection uConn = url.openConnection();
uConn.setDefaultUseCaches(false);
}
public static String guessMimeType(String path) {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = null;
try {
contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (contentTypeFor == null) {
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
}
@Test
public void testContentLength() throws Exception {
File f = new File("test/webresources/war-url-connection.war");
String fileUrl = f.toURI().toURL().toString();
URL indexHtmlUrl = new URL("jar:war:" + fileUrl +
"*/WEB-INF/lib/test.jar!/META-INF/resources/index.html");
URLConnection urlConn = indexHtmlUrl.openConnection();
urlConn.connect();
int size = urlConn.getContentLength();
Assert.assertEquals(137, size);
}
private static TrackingInputStream getInputStream(URLConnection conn) throws IOException {
String encoding = conn.getContentEncoding();
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream()));
}
return new SimpleTrackingInputStream(conn.getInputStream());
}
private AddDeploymentPlanBuilder add(String name, String commonName, URL url) throws IOException, DuplicateDeploymentNameException {
URLConnection conn = url.openConnection();
conn.connect();
InputStream stream = conn.getInputStream();
try {
return add(name, commonName, stream);
}
finally {
try { stream.close(); } catch (Exception ignored) {}
}
}
private static String getHtml(String address){
StringBuffer html = new StringBuffer();
String result = null;
try{
URL url = new URL(address);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; NT 5.1; GTB5; .NET CLR 2.0.50727; CIBA)");
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
try{
String inputLine;
byte[] buf = new byte[4096];
int bytesRead = 0;
while (bytesRead >= 0) {
inputLine = new String(buf, 0, bytesRead, "ISO-8859-1");
html.append(inputLine);
bytesRead = in.read(buf);
inputLine = null;
}
buf = null;
}finally{
in.close();
conn = null;
url = null;
}
result = new String(html.toString().trim().getBytes("ISO-8859-1"), "gb2312").toLowerCase();
}catch (Exception e) {
e.printStackTrace();
return null;
}finally{
html = null;
}
return result;
}
URLConnection getConnection(JarFile jarFile) throws IOException {
URL u;
synchronized (instance) {
u = urlCache.get(jarFile);
}
if (u != null)
return u.openConnection();
return null;
}
private static String readBuildDateFromManifest() {
try {
final URLConnection jarConnection = getLocationOfClass().openConnection();
if ( !(jarConnection instanceof JarURLConnection) ) {
return null;
}
final JarURLConnection conn = (JarURLConnection) jarConnection;
final Manifest mf = conn.getManifest();
final Attributes atts = mf.getMainAttributes();
return atts.getValue( "Build-Time" );
} catch ( final IOException e ) {
return null;
}
}
private URLConnection setupConnection(URL url) throws IOException
{
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000);
connection.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");
return connection;
}
@Override
public URLConnection openConnection ( URL u ) throws IOException {
if ( log.isDebugEnabled() ) {
log.debug("Opening file " + u);
}
return new SmbFile(u, getTransportContext());
}