自定义请求生成器Apache

时间:2018-08-17 10:15:42

标签: java apache-httpclient-4.x

我需要一个自定义请求构建器,该构建器将返回实现HttpEntityEnclosingRequest的实例。以前,我使用的RequestBuilder达不到我的目的。

我之前所做的事情

public class SharePointRequestBuilder {
  //default mime type
  private static final String JSON_ODATA_VERBOSE_MIME_TYPE = "application/json;odata=verbose";

  private RequestBuilder delegate;

  private SharePointRequestBuilder(RequestBuilder delegate) {
    this.delegate = delegate;
  }

  public static final SharePointRequestBuilder get(String uri)
      throws URISyntaxException {
    return new SharePointRequestBuilder(RequestBuilder.get(new URI(uri)));
  }

  public static final SharePointRequestBuilder post(String uri)
      throws URISyntaxException {
    return new SharePointRequestBuilder(RequestBuilder.post(new URI(uri)));
  }

  public final SharePointRequestBuilder setEntity(String entity, ContentType contentType) {
    delegate.setEntity(new StringEntity(entity, contentType));
    return this;
  }

  public final SharePointRequestBuilder setEntity(String entity, Charset charset) {
    delegate.setEntity(new StringEntity(entity, charset));
    return this;
  }

  public final SharePointRequestBuilder setEntity(HttpEntity entity) {
    delegate.setEntity(entity);
    return this;
  }

  public final SharePointRequestBuilder setHeader(String name, String value) {
    delegate.setHeader(name, value);
    return this;
  }

  public final SharePointRequestBuilder setHeaders(List<Header> headers) {
    headers.forEach(p-> delegate.setHeader(p));
    return this;
  }

  public final SharePointRequestBuilder withDefaultMimeType() {
    setHeader(CONTENT_TYPE, JSON_ODATA_VERBOSE_MIME_TYPE);
    setHeader(ACCEPT, JSON_ODATA_VERBOSE_MIME_TYPE);
    return this;
  }

  public final HttpUriRequest build() {
    return delegate.build();
  }
}

当我将调用build()方法时,我期望一个实例实现HttpEntityEnclosingRequest而不是HttpUriRequest。有什么方法可以自定义build()方法?

请帮助。

0 个答案:

没有答案