How to clear HTTP from Java?
•
Java
I am trying to perform purge using httpurlconnection as follows:
private void callVarnish(URL url) { HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(PURGE_METHOD); conn.setDoOutput(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Host","www.somehost.com"); conn.connect(); System.out.print(conn.getResponseCode() + " " + conn.getResponseMessage()); } catch (Exception e) { log.error("Could not call varnish: " + e); } finally { if (conn != null) { conn.disconnect(); } } }
But I got:
08:56:31,813 ERROR [VarnishHandler] Could not call varnish: java.net.ProtocolException: Invalid HTTP method: PURGE
Curl is OK:
Curl - I - x purge - H "Moderator: www.somehost. Com" someurl
HTTP/1.1 404 Not in cache. Server: Varnish Content-Type: text/html; charset=utf-8 Retry-After: 5 Content-Length: 401 Accept-Ranges: bytes Date: Thu,18 Oct 2012 06:40:19 GMT X-Varnish: 1611365598 Age: 0 Via: 1.1 varnish Connection: close X-Cache: MISS
What should I do? Do I need to curl from Java or are there other libraries I can use?
Solution
You can use Apache's httpclient Library: http://hc.apache.org/httpcomponents-client-ga/
You can use basichttprequest or implement your own httppurge class that extends httprequestbase
You can find a quick start guide here: http://hc.apache.org/httpcomponents-client-ga/quickstart.html
Example:
DefaultHttpClient httpclient = new DefaultHttpClient(); BasicHttpRequest httpPurge = new BasicHttpRequest("PURGE","www.somehost.com") HttpResponse response = httpclient.execute(httpPurge);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码