Java URLConnection .setUseCaches (boolean usecaches)
Syntax
URLConnection.setUseCaches(boolean usecaches) has the following syntax.
public void setUseCaches(boolean usecaches)
Example
In the following code shows how to use URLConnection.setUseCaches(boolean usecaches) method.
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;
//www . j a v a 2 s . c o m
public class Main {
public static void main(String args[])throws Exception {
String sessionCookie = null;
URL url = new java.net.URL("http://127.0.0.1/yourServlet");
URLConnection con = url.openConnection();
if (sessionCookie != null) {
con.setRequestProperty("cookie", sessionCookie);
}
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteOut);
out.flush();
byte buf[] = byteOut.toByteArray();
con.setRequestProperty("Content-type", "application/octet-stream");
con.setRequestProperty("Content-length", "" + buf.length);
DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
dataOut.write(buf);
dataOut.flush();
dataOut.close();
DataInputStream in = new DataInputStream(con.getInputStream());
int count = in.readInt();
in.close();
if (sessionCookie == null) {
String cookie = con.getHeaderField("set-cookie");
if (cookie != null) {
sessionCookie = parseCookie(cookie);
System.out.println("Setting session ID=" + sessionCookie);
}
}
System.out.println(count);
}
public static String parseCookie(String raw) {
String c = raw;
if (raw != null) {
int endIndex = raw.indexOf(";");
if (endIndex >= 0) {
c = raw.substring(0, endIndex);
}
}
return c;
}
}