使用 org.apache.httpcomponents 4.2.1:
班级:
import org.apache.http.client.methods.HttpRequestBase;
import java.net.URI;
public class HttpPurge extends HttpRequestBase {
public final static String METHOD_NAME = "PURGE";
public HttpPurge() {
super();
}
@Override
public String getMethod() {
return METHOD_NAME; //To change body of implemented methods use File | Settings | File Templates.
}
public HttpPurge(final String uri) {
super();
setURI(URI.create(uri));
}
public String getName() {
return "PURGE";
}
}
来电:
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import test.HttpPurge
private void callVarnish(URL url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPurge httpPurge = new HttpPurge(url.toString());
Header header = new BasicHeader("Host", "www.somewhere.se");
httpPurge.setHeader(header);
try {
HttpResponse response = httpclient.execute(httpPurge);
System.out.print("-------------------------------------");
System.out.println(response.getStatusLine());
System.out.print("-------------------------------------");
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity);
}
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection and release it back to the connection manager.
httpPurge.abort();
}
}
使用已弃用的 org.apache.commons.httpclient.HttpMethodBase:
班级:
import org.apache.commons.httpclient.HttpMethodBase;
public class PurgeMethod extends HttpMethodBase {
public PurgeMethod() {
super();
setFollowRedirects(true);
}
public PurgeMethod(String url) {
super(url);
setFollowRedirects(true);
}
public String getName() {
return "PURGE";
}
}
来电:
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
private void callVarnish(URL url) {
HttpClient client = new HttpClient();
HttpMethod method = new PurgeMethod(url.toString());
try {
int status = 0;
status = client.executeMethod(method);
log.debug(status);
} catch (Exception e) {
// something
} finally {
method.releaseConnection();
}
}