JSP 개발 중 Apache-HTPClient 사용자 가 검증 한 실례 상세 설명

JSP 개발 중 Apache-HTPClient 사용자 가 검증 한 실례 상세 설명
선언:
마이크로 서비스 프레임 워 크 를 제외 한 시스템 에서 우 리 는 http Client 를 사용 하여 인터페이스 호출 을 하 는 문 제 를 자주 만 날 수 있 습 니 다.화이트 리스트 설정 을 제외 하고 인터페이스 호출 을 할 때 인증 이 필요 할 때 가 많 습 니 다.공식 문 서 를 뒤 져 보 니 해결 방법 이 많 지만 실제 업무 장면 에 부합 되 지 않 아 간단 하고 거 친 해결 방법 을 제공 합 니 다.
해결 방법:요청 헤드 를 이용 하여 인증 정 보 를 저장 합 니 다.
구현 코드:

public class HttpClientUtils {

  protected static final Logger LOG = LoggerFactory.getLogger(HttpClientUtils.class);

  private static final String AUTHENKEY = "Authorization";

  private static final String BASICKEY = "Basic ";

  public static String getConnect(String url,String username,String password) {

    CloseableHttpResponse response = null;

    CloseableHttpClient client = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet(url);
    Base64 token = new Base64();
    String authenticationEncoding = token.encodeAsString(new String(username + ":" + password).getBytes());

    httpGet.setHeader(AUTHENKEY, BASICKEY + authenticationEncoding);

    String responseContent = "";
    try {
      response = client.execute(httpGet);

      HttpEntity entity = response.getEntity();

      responseContent = EntityUtils.toString(entity, "UTF-8");

    } catch (IOException e) {
      LOG.error(e.toString());
    } finally {
      if (response != null) {
        try {
          response.close();
        } catch (IOException e) {
          LOG.error(e.toString());
        }
      }

      if (client != null) {
        try {
          client.close();
        } catch (IOException e) {
          LOG.error(e.toString());
        }
      }
    }

    return responseContent;
  }


}

이상 은 Apache-HTPClient 사용자 가 검증 한 실례 입 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주시 거나 본 사이트 커 뮤 니 티 에 가서 토론 을 나 누 십시오.읽 어 주 셔 서 감사합니다. 도움 이 되 셨 으 면 좋 겠 습 니 다.본 사이트 에 대한 지원 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기