gpt4 book ai didi

java - 如何从 Java 执行 HTTP 清除?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:10:28 25 4
gpt4 key购买 nike

我正在尝试像这样使用 HttpUrlConnection 执行 PURGE:

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();
}
}
}

但是我得到:

08:56:31,813 ERROR [VarnishHandler] Could not call varnish: java.net.ProtocolException: Invalid HTTP method: PURGE

使用 curl 没有问题:

curl -I -X PURGE -H "Host: 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

那我该怎么做呢?我需要从 Java 中 curl 还是可以使用其他一些库?

最佳答案

您可以使用 Apache 的 HttpClient 库:http://hc.apache.org/httpcomponents-client-ga/

您可以使用 BasicHttpRequest或者实现你自己的 HttpPurge 类扩展 HttpRequestBase .

您可以在此处找到快速入门指南:http://hc.apache.org/httpcomponents-client-ga/quickstart.html

例子:

DefaultHttpClient httpclient = new DefaultHttpClient();
BasicHttpRequest httpPurge = new BasicHttpRequest("PURGE", "www.somehost.com")
HttpResponse response = httpclient.execute(httpPurge);

关于java - 如何从 Java 执行 HTTP 清除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12949457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com