All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ifengxue.http.executor.AbstractHttpExecutor Maven / Gradle / Ivy

/*
 * Copyright 2018 https://www.ifengxue.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ifengxue.http.executor;

import com.ifengxue.http.proxy.HttpClientConfig;
import java.nio.charset.Charset;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.impl.client.CloseableHttpClient;

/**
 * http执行器基类
 */
public abstract class AbstractHttpExecutor implements HttpExecutor {

  protected Charset charset = HttpClientConfig.UTF_8;
  protected CloseableHttpClient httpClient;
  protected HttpHost proxy;
  protected int socketTimeout = -1;
  protected int connectTimeout = -1;

  @Override
  public void setCharset(Charset charset) {
    this.charset = charset;
  }

  @Override
  public Charset getCharset() {
    return charset;
  }

  @Override
  public void setHttpClient(CloseableHttpClient httpClient) {
    this.httpClient = httpClient;
  }

  @Override
  public void setProxy(HttpHost proxy) {
    this.proxy = proxy;
  }

  @Override
  public void setTimeout(int socketTimeout, int connectTimeout) {
    this.socketTimeout = socketTimeout;
    this.connectTimeout = connectTimeout;
  }

  /**
   * 创建配置
   *
   * @return 如果没有自定义配置,返回值为null
   */
  protected RequestConfig createConfig() {
    if (proxy == null && socketTimeout < 0 && connectTimeout < 0) {
      return null;
    }
    Builder builder = RequestConfig.custom();
    if (proxy != null) {
      builder.setProxy(proxy);
    }
    if (socketTimeout >= 0) {
      builder.setSocketTimeout(socketTimeout);
    }
    if (connectTimeout >= 0) {
      builder.setConnectTimeout(connectTimeout);
    }
    return builder.build();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy