1

使用 Clojure 1.4 (Java 7) 和 clj-http (0.6.0) 库。执行获取请求时,会自动包含 Content-Length 标头并将其设置为零。一些服务器(例如 lighttpd)不喜欢这样,并以 Bad Request 响应。是否可以删除上述标题或使库默认不包含它?我在文档中找不到任何相关的东西,谷歌搜索只给了我this,这并没有真正的帮助。

4

1 回答 1

1

如果我尝试:

(client/get "http://thepiratebay.se" {:debug true})

我得到:

Request: nil
{:scheme :http,
 :http-url "http://thepiratebay.se",
 :request-method :get,
 :query-string nil,
 :uri "",
 :server-name "thepiratebay.se",

 :headers {"accept-encoding" "gzip, deflate"},
 :debug true,
 :body-type nil,
 :server-port nil,
 :body nil,
 :user-info nil}
HttpRequest:
{:requestLine #<BasicRequestLine GET http://thepiratebay.se HTTP/1.1>,
 :protocolVersion #<HttpVersion HTTP/1.1>,
 :params
 #<BasicHttpParams org.apache.http.params.BasicHttpParams@5b14a306>,
 :method "GET",
 :entity nil,
 :class
 clj_http.core.proxy$org.apache.http.client.methods.HttpEntityEnclosingRequestBase$0,
 :allHeaders
 [#<BasicHeader Connection: close>,
  #<BasicHeader accept-encoding: gzip, deflate>],
 :aborted false,
 :URI #<URI http://thepiratebay.se>}   

这会产生 400 错误。我尝试直接使用 Apache HttpClient 在 Java 中重现它:

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.HttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.Header;

public class Get {
  public static void main(String args[]) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(args[0]);
    httpget.addHeader("Connection", "close");
    httpget.addHeader("accept-encoding", "gzip, deflate");
    Header[] headers = httpget.getAllHeaders();
    for (Header h : headers) {
      System.out.println(h.getName() + ", " + h.getValue());
    }
    System.out.println();
    HttpResponse response = httpclient.execute(httpget);
    System.out.println(response);
  }
}

但是,这很好用。我的猜测是,在调用 HttpClient 之前,clj-http 正在执行一些强制响应中的空正文的操作,因此 HttpClient 将标头 Content-Length 设置为 0。如果您查看源代码,则 clj-http 不会设置标头。我会将此作为 clj-http 的问题提交。

https://github.com/dakrone/clj-http/issues

于 2012-12-09T17:14:26.027 回答