下面列出了java.net.URLConnection#setUseCaches ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Calls the LoLA service with the given PNML under the given URL.
* @param pnml of the Petri net
* @param address - URL of the LoLA service
* @return text response from LoLA
* @throws IOException
*/
private static String callLola(String pnml, String address) throws IOException {
URL url = new URL(address);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setReadTimeout(TIMEOUT);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
// send pnml
writer.write("input=" + URLEncoder.encode(pnml, "UTF-8"));
writer.flush();
// get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
writer.close();
reader.close();
return answer.toString();
}
private Collection<X509CRL> loadFromURI(CertificateFactory cf, URI remoteURI) throws GeneralSecurityException {
try {
logger.debugf("Loading CRL from %s", remoteURI.toString());
URLConnection conn = remoteURI.toURL().openConnection();
conn.setDoInput(true);
conn.setUseCaches(false);
X509CRL crl = loadFromStream(cf, conn.getInputStream());
return Collections.singleton(crl);
}
catch(IOException ex) {
logger.errorf(ex.getMessage());
}
return Collections.emptyList();
}
public static String getUrl(URL url) throws IOException {
StringBuilder sb = new StringBuilder(5000);
if(url != null) {
URLConnection con = url.openConnection();
Wandora.initUrlConnection(con);
con.setUseCaches(false);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
}
in.close();
}
return sb.toString();
}
@Override
public byte[] call() {
OutputStream out = null;
InputStream inputStream = null;
byte[] result = null;
try {
URLConnection connection = createConnection();
connection.setUseCaches(useCaches);
connection.setDoInput(true);
if (content != null) {
connection.setDoOutput(true);
out = connection.getOutputStream();
Utils.write(content, out);
}
inputStream = connection.getInputStream();
result = Utils.toByteArray(maxInputSize > 0? new MaxSizeInputStream(inputStream, maxInputSize, url): inputStream);
} catch (IOException e) {
throw new DSSException(String.format(ERROR_MESSAGE, url, e.getMessage()), e);
} finally {
Utils.closeQuietly(out);
Utils.closeQuietly(inputStream);
}
return result;
}
/**
* Parse the content of the given URL as a provider-configuration file.
*/
private Iterator<String> parse(URL u) {
Set<String> names = new LinkedHashSet<>(); // preserve insertion order
try {
URLConnection uc = u.openConnection();
uc.setUseCaches(false);
try (InputStream in = uc.getInputStream();
BufferedReader r
= new BufferedReader(new InputStreamReader(in, UTF_8.INSTANCE)))
{
int lc = 1;
while ((lc = parseLine(u, r, lc, names)) >= 0);
}
} catch (IOException x) {
fail(service, "Error accessing configuration file", x);
}
return names.iterator();
}
public String doUrl (URL url) throws IOException {
StringBuilder sb = new StringBuilder(5000);
if (url != null) {
URLConnection con = url.openConnection();
Wandora.initUrlConnection(con);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-type", "text/plain");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName(defaultEncoding)));
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
if(!(s.endsWith("\n") || s.endsWith("\r"))) sb.append("\n");
}
in.close();
} catch (Exception ex) {
log("Authentication failed. Check API Key.");
}
}
return sb.toString();
}
@Override
protected NonClosingJarInputStream createJarInputStream() throws IOException {
JarURLConnection jarConn = (JarURLConnection) getJarFileURL().openConnection();
URL resourceURL = jarConn.getJarFileURL();
URLConnection resourceConn = resourceURL.openConnection();
resourceConn.setUseCaches(false);
return new NonClosingJarInputStream(resourceConn.getInputStream());
}
/**
* Resolves the requested external entity. This is the default
* implementation of the {@code EntityResolver} interface. It checks
* the passed in public ID against the registered entity IDs and uses a
* local URL if possible.
*
* @param publicId the public identifier of the entity being referenced
* @param systemId the system identifier of the entity being referenced
* @return an input source for the specified entity
* @throws org.xml.sax.SAXException if a parsing exception occurs
*/
@SuppressWarnings("resource") // The stream is managed by the InputSource returned by this method.
@Override
public InputSource resolveEntity(final String publicId, final String systemId)
throws SAXException
{
// Has this system identifier been registered?
URL entityURL = null;
if (publicId != null)
{
entityURL = getRegisteredEntities().get(publicId);
}
if (entityURL != null)
{
// Obtain an InputSource for this URL. This code is based on the
// createInputSourceFromURL() method of Commons Digester.
try
{
final URLConnection connection = entityURL.openConnection();
connection.setUseCaches(false);
final InputStream stream = connection.getInputStream();
final InputSource source = new InputSource(stream);
source.setSystemId(entityURL.toExternalForm());
return source;
}
catch (final IOException e)
{
throw new SAXException(e);
}
}
// default processing behavior
return null;
}
private NonClosingJarInputStream createJarInputStream() throws IOException {
JarURLConnection jarConn = (JarURLConnection) url.openConnection();
URL resourceURL = jarConn.getJarFileURL();
URLConnection resourceConn = resourceURL.openConnection();
resourceConn.setUseCaches(false);
return new NonClosingJarInputStream(resourceConn.getInputStream());
}
private static String getClasspathResourceText(URL requestURL) throws IOException {
URLConnection connection = requestURL.openConnection();
connection.setUseCaches(false);
try (Reader r = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)) {
return CharStreams.toString(r);
}
}
public static InputStream getSettingsInputStream() {
try {
URL url = TabooLibServer.class.getClassLoader().getResource("__resources__/settings.properties");
if (url == null) {
return null;
} else {
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
return connection.getInputStream();
}
} catch (IOException ignored) {
return null;
}
}
private void doPost(String url, String content) throws IOException {
URL urlObj = new URL(url);
URLConnection conn = urlObj.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(content);
out.flush();
out.close();
conn.getInputStream().close();
}
protected String doUrl (URL url) throws IOException {
StringBuilder sb = new StringBuilder(5000);
if (url != null) {
URLConnection con = url.openConnection();
Wandora.initUrlConnection(con);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-type", "text/plain");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName(defaultEncoding)));
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
if(!(s.endsWith("\n") || s.endsWith("\r"))) sb.append("\n");
}
in.close();
}
catch (Exception ex) {
log(ex);
}
}
return sb.toString();
}
private static URLConnection openConnection(URL url) throws IOException {
final URLConnection connection = url.openConnection();
connection.setUseCaches(false);
connection.addRequestProperty("Cache-Control", "no-cache");
connection.connect();
return connection;
}
private static InputStream getInputStream(ClassLoader loader, String resourceName, boolean reload)
throws IOException {
URL url = loader.getResource(resourceName);
if (url == null) {
return null;
}
URLConnection connection = url.openConnection();
connection.setUseCaches(!reload);
return connection.getInputStream();
}
public static OutputStream createOutputStream(String uri) throws IOException {
// URI was specified. Handle relative URIs.
final String expanded = XMLEntityManager.expandSystemId(uri, null, true);
final URL url = new URL(expanded != null ? expanded : uri);
OutputStream out = null;
String protocol = url.getProtocol();
String host = url.getHost();
// Use FileOutputStream if this URI is for a local file.
if (protocol.equals("file")
&& (host == null || host.length() == 0 || host.equals("localhost"))) {
File file = new File(getPathWithoutEscapes(url.getPath()));
if (!file.exists()) {
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
}
out = new FileOutputStream(file);
}
// Try to write to some other kind of URI. Some protocols
// won't support this, though HTTP should work.
else {
URLConnection urlCon = url.openConnection();
urlCon.setDoInput(false);
urlCon.setDoOutput(true);
urlCon.setUseCaches(false); // Enable tunneling.
if (urlCon instanceof HttpURLConnection) {
// The DOM L3 REC says if we are writing to an HTTP URI
// it is to be done with an HTTP PUT.
HttpURLConnection httpCon = (HttpURLConnection) urlCon;
httpCon.setRequestMethod("PUT");
}
out = urlCon.getOutputStream();
}
return out;
}
public static void uploadFileToS3(String filePath, String presignedUrl) {
try {
URLConnection urlconnection = null;
File appFile = new File(filePath);
URL url = new URL(presignedUrl);
urlconnection = url.openConnection();
urlconnection.setUseCaches(false);
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
if (urlconnection instanceof HttpURLConnection) {
((HttpURLConnection) urlconnection).setRequestMethod("PUT");
((HttpURLConnection) urlconnection).setRequestProperty("Content-Type", "application/octet-stream");
((HttpURLConnection) urlconnection).setRequestProperty("x-amz-tagging", "unsaved=true");
((HttpURLConnection) urlconnection).setRequestProperty("Content-Length", getFileSizeBytes(appFile));
((HttpURLConnection) urlconnection).connect();
}
BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
FileInputStream bis = new FileInputStream(appFile);
System.out.println("Total file size to read (in bytes) : " + bis.available());
int i;
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.close();
bis.close();
InputStream inputStream;
int responseCode = ((HttpURLConnection) urlconnection).getResponseCode();
if ((responseCode >= 200) && (responseCode <= 202)) {
inputStream = ((HttpURLConnection) urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) > 0) {
System.out.println(j);
}
} else {
inputStream = ((HttpURLConnection) urlconnection).getErrorStream();
}
((HttpURLConnection) urlconnection).disconnect();
System.out.println("uploadFileToS3: " + ((HttpURLConnection) urlconnection).getResponseMessage());
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public TGShareSongResponse getResponse() throws Throwable {
URL url = new URL(TGCommunityWeb.getHomeUrl(this.context) + "/rd.php/sharing/tuxguitar/upload.do");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDARY);
DataOutputStream out = new DataOutputStream( conn.getOutputStream() );
// auth
out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
out.writeBytes("Content-Disposition: form-data; name=\"auth\";" + EOL);
out.writeBytes(EOL);
out.writeBytes(this.auth.getAuthCode());
out.writeBytes(EOL);
// title
out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
out.writeBytes("Content-Disposition: form-data; name=\"title\";" + EOL);
out.writeBytes(EOL);
out.writeBytes(this.file.getTitle());
out.writeBytes(EOL);
// description
out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
out.writeBytes("Content-Disposition: form-data; name=\"description\";" + EOL);
out.writeBytes(EOL);
out.writeBytes(this.file.getDescription());
out.writeBytes(EOL);
// tagkeys
out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
out.writeBytes("Content-Disposition: form-data; name=\"tagkeys\";" + EOL);
out.writeBytes(EOL);
out.writeBytes(this.file.getTagkeys());
out.writeBytes(EOL);
// file
out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
out.writeBytes("Content-Disposition: form-data; name=\"fileName\";" + " filename=\"" + this.file.getFilename() +"\"" + EOL);
out.writeBytes(EOL);
out.write( this.file.getFile() );
out.writeBytes(EOL);
out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + BOUNDARY_SEPARATOR + EOL);
out.flush();
out.close();
return new TGShareSongResponse( conn.getInputStream() );
}
/**
* Query an external RFC2483 resolver.
*
* @param resolver The URL of the RFC2483 resolver.
* @param command The command to send the resolver.
* @param arg1 The first argument to the resolver.
* @param arg2 The second argument to the resolver, usually null.
*
* @return The Resolver constructed.
*/
protected Resolver queryResolver(String resolver,
String command,
String arg1,
String arg2) {
InputStream iStream = null;
String RFC2483 = resolver + "?command=" + command
+ "&format=tr9401&uri=" + arg1
+ "&uri2=" + arg2;
String line = null;
try {
URL url = new URL(RFC2483);
URLConnection urlCon = url.openConnection();
urlCon.setUseCaches(false);
Resolver r = (Resolver) newCatalog();
String cType = urlCon.getContentType();
// I don't care about the character set or subtype
if (cType.indexOf(";") > 0) {
cType = cType.substring(0, cType.indexOf(";"));
}
r.parseCatalog(cType, urlCon.getInputStream());
return r;
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.UNPARSEABLE) {
catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483);
} else if (cex.getExceptionType()
== CatalogException.UNKNOWN_FORMAT) {
catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483);
}
return null;
} catch (MalformedURLException mue) {
catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483);
return null;
} catch (IOException ie) {
catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483);
return null;
}
}
/**
* Set the {@link URLConnection#setUseCaches "useCaches"} flag on the given
* connection, preferring {@code false} but leaving the flag at {@code true}
* for JNLP based resources.
*
* @param con
* the URLConnection to set the flag on
*/
public static void useCachesIfNecessary(URLConnection con) {
con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));
}