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

com.ifengxue.http.proxy.BasicAuthInterceptor Maven / Gradle / Ivy

/*
 * Copyright 2019 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.proxy;

import com.ifengxue.http.HttpClientException;
import com.ifengxue.http.annotation.BodyType;
import com.ifengxue.http.annotation.ResponseType;
import com.ifengxue.http.executor.HttpExecutor;
import com.ifengxue.http.executor.Request;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import lombok.NonNull;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHeaders;

/**
 * http basic auth 拦截器
* 参考维基百科 */ public class BasicAuthInterceptor extends InterceptorAdaptor { private final String username; private final String password; private final Charset charset; public BasicAuthInterceptor(String username, String password) { this(username, password, StandardCharsets.UTF_8); } /** * @param username 用户名 * @param password 密码 */ public BasicAuthInterceptor(@NonNull String username, String password, Charset charset) { this.username = username; this.password = password; this.charset = charset; } @Override public T beforeRequest(Method method, Request request, BodyType bodyType, ResponseType responseType, HttpExecutor executor) throws HttpClientException { String base64 = Base64 .encodeBase64String((username + ":" + Optional.ofNullable(password).orElse("")).getBytes(charset)); request.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + base64); return null; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy