본문 바로가기
study/TIP

request path

by 휘루걸음 2011. 7. 29.
728x90
반응형

Java에서 HTTP 요청을 보내는 경우, 요청 경로(request path)를 설정하는 방법은 주로 다음과 같은 방식으로 이루어집니다.

반응형
728x90

 

  1. HttpURLConnection 사용: Java에서 HTTP 요청을 보낼 때 가장 기본적으로 사용되는 클래스 중 하나인 HttpURLConnection을 사용하여 요청 경로를 설정할 수 있습니다.
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.io.*;
    
    public class HttpRequestExample {
        public static void main(String[] args) throws IOException {
            URL url = new URL("http://example.com/api/path/to/resource");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET"); // 예시로 GET 요청을 보내는 경우
            // 다른 설정 (헤더 추가, 바디 데이터 전송 등)
    
            // 요청을 보내기 전에 연결 설정 등을 추가할 수 있음
    
            int responseCode = con.getResponseCode();
            // 응답 처리 등
        }
    }​

  2. HttpClient 라이브러리 사용: Apache HttpClient 또는 Java 11부터 제공되는 HttpClient를 사용하여 요청을 보낼 수 있습니다. 이를 통해 요청 경로를 설정할 수 있습니다.
    // Apache HttpClient 사용 예시
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.HttpResponse;
    import java.io.*;
    
    public class HttpRequestExample {
        public static void main(String[] args) throws IOException {
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet request = new HttpGet("http://example.com/api/path/to/resource");
            // 다른 설정 (헤더 추가, 바디 데이터 전송 등)
    
            // 요청을 보내기 전에 연결 설정 등을 추가할 수 있음
    
            HttpResponse response = httpClient.execute(request);
            // 응답 처리 등
        }
    }

 

위 예시들은 간단한 GET 요청을 보내는 예시입니다. 요청 메서드(GET, POST, PUT, DELETE 등)나 헤더 설정, 요청 본문(body) 추가 등을 위해서는 각각의 라이브러리에서 제공하는 방법을 참조하여 설정해야 합니다.

 

 

 

 

#code sample

request.getContextPath(); 
request.getRequestURI(); 
request.getHeader("REFERER"); 
request.getRealPath("/")
 
 
 
request.getContextPath()는 프로젝트의 Context path명을 반환한다.
 
요청 : http://localhost:8080/example/test.jsp 
 
리턴값 : /example
 
 
 
 
request.getRequestURI()는 웹전체 경로(프로젝트명+ 파일 경로)까지 반환한다.
 
요청 : http://localhost:8080/example/test.jsp
 
리턴값 : /example/test.jsp 
 
 
 
 
request.getHeader("REFERER")는 요청을 한 부모요청의 URL주소를 반환한다.
 
현재 페이지:  http://localhost:8080/example/test1.do
 
요청 페이지 :  http://localhost:8080/example/test.do
 
리턴값 : http://localhost:8080/example/test.do
 
 
 
 
request.getRealPath("/")는 서버 또는 로컬의 웹애플리케애션 서버의 docBase 설정값을 반환한다.
 
요청 : http://localhost:8080/example/test.jsp
 
리턴값 : D:\\Project\\webapps\\example
728x90
반응형

'study > TIP' 카테고리의 다른 글

php 문자열 함수  (0) 2012.02.27
fat32 usb convert to ntfs  (0) 2011.12.25
SmartEditor with upload  (0) 2011.12.09
프로젝트 산출 목록  (0) 2011.12.02
정규식  (0) 2010.12.10