2 minute read

HttpUtil.java

// Apache HttpCore » 4.4.15 필요
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

// Apache HttpClient » 4.5.13 필요 
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

Http 통신이 대하여
💡 프로그래밍에서 통신하기 위한 관련 라이브러리는 종류가 많다.
💡 메이븐레파지토리 기준에서 점유율을 확인 후 작성했다.
💡 가장 대중적이고 가장 많이 사용하는 라이브러리를 선택했다.(아파치 4버전)
💡 아파치의 라이브러리가 최근엔 5버전으로 배포중인듯하다.

Apache HttpCore » 4.4.15
💡 이 마지막 버전의 라이브러리를 추가해주어야 위 클래스 임포트가 가능하다.
💡 4버전의 마지막인 4.4.16 를 추가하면 임포트 불가능함을 확인했다.

Apache HttpClient » 4.5.13
💡 위와 동일하다.

다운로드 경로
Apache HttpCore » 4.4.15: 바로가기 링크
Apache HttpClient » 4.5.13: 바로가기 링크

connectGET() : GET요청 후 String 얻기

	/*********************
	 * GET 요청 후 응답결과를 String 으로 받는다.
	 * 
	 * @param 요청 URL주소
	 * @return String
	 * @throws IOException 
	 * @throws ClientProtocolException
	 *********************/
	public static String connectGET(String containParamURL) throws ClientProtocolException, IOException 
	{
	  BufferedReader br = null;
	  StringBuilder builder = new StringBuilder();
	  HttpClient httpClient = HttpClients.createDefault();
	  HttpGet get = null;

	  try
	  {
	    get = new HttpGet(containParamURL);

	    HttpResponse response = httpClient.execute(get);
	    int status = response.getStatusLine().getStatusCode();

	    if(status >= 200 && status < 300) 
	    {
	      HttpEntity entity = response.getEntity();

	      br = new BufferedReader(new InputStreamReader(entity.getContent()));
	      String line = null;
	      
	      while((line = br.readLine()) != null) {
	        builder.append(line);
	      }
	    }
	  }
	  finally
	  {
	    if(br != null) {
	      br.close();
	    }
	    if(get != null) {
	      get.releaseConnection();
	    }
	  }

	  return builder.toString();
	}

isConnectURL() : URL 연결이 가능여부 확인

	/*********************
	 * 해당 URL에 연결이 가능한지 확인한다.
	 * 
	 * @param 요청 URL주소
	 * @return boolean
	 * @throws
	 *********************/
	public static Boolean isConnectURL(String connectURL) 
	{  
	  try
	  {
	    URL url = new URL(connectURL);

	    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	    if (url.toString().startsWith("https")) {
	      connection = (HttpsURLConnection) url.openConnection();
	    }
	    ((HttpURLConnection)connection).setRequestMethod("HEAD");

	    int responseCode = connection.getResponseCode();
	    System.out.println("[연결 가능합니다!.] isConnectURL("+ connectURL + ") \n ==> responseCode: " + responseCode);

	    if (connection != null) {
	      connection.disconnect();
	    }
	    if (responseCode == 503) {
	      return false;
	    }
	    if (responseCode == HttpURLConnection.HTTP_OK) {
	      return true;
	    }
	  }
	  catch (MalformedURLException e)
	  {
	    System.out.println("isConnectURL("+ connectURL + ") \n ==> MalformedURLException: " + e.toString());
	    return false;
	  }
	  catch (ConnectException e)
	  {
	    System.out.println("isConnectURL("+ connectURL + ") \n ==> ConnectException: " + e.toString());
	    return false;
	  }
	  catch (IOException e)
	  {
	    System.out.println("isConnectURL("+ connectURL + ") \n ==> IOException: " + e.toString());
	  }

	  return true;
	}

connectCaptureGET() : GET요청 후 캡처한 응답별 String 얻기

	/*********************
	 * GET 요청 후 타서버 접속하여 응답결과를 String 으로 받는다.
	 * 타겟 서버측 내부에서 로드밸런싱 등의 리다이렉트 처리가 일어나면
   * 중간에서 응답을 캡처한다.
   * 
	 * @param 요청 URL주소
	 * @return String
	 * @throws IOException 
	 * @throws ClientProtocolException
	 *********************/
	public static String connectCaptureGET(String containParamURL) throws ClientProtocolException, IOException 
	{
    final boolean[] isRedirect = {false};
	  StringBuilder builder = new StringBuilder();
    HttpGet get = null;

    // Yarn Resource 서버측 로드밸런싱으로 인한 HTTP 응답 인터셉터 캡처 구현
    HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
      @Override
      public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 307) isRedirect[0] = true; //리다이렉트 캡처
      }
    };

    //HttpClient 생성 및 응답 인터셉터 등록
    CloseableHttpClient httpClient = HttpClient.custom();
            .addInterceptorLast(responseInterceptor);
            .build();
	  try
	  {
	    get = new HttpGet(containParamURL);

	    HttpResponse response = httpClient.execute(get);
	    int status = response.getStatusLine().getStatusCode();

	    if(status >= 200 && status < 300) 
	    {
        if(isRedirect[0]) return null; //307 로드밸런싱시 return
	      HttpEntity entity = response.getEntity();

        // try-with-resources 자원해제
        try (BufferedReader br = new BufferedReader(new InputStreamReader(entitiy.getContent()));) {
          String line = null;
          while((line = br.readLine()) != null) {
	          builder.append(line);
	        }
        }	      
	    }
	  }
	  finally
	  {
      try {
        httpClient.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
	  return builder.toString();
	}

Tags:

Categories:

Updated:

Leave a comment