본문 바로가기
java

[java][프록시] 네트워크 프록시 설정

by hs_seo 2016. 11. 8.

자바에서 네트워크 프로그래밍을 하는 중에 프록시를 설정하는 방법은 

Proxy 클래스를 이용하는 것과 시스템 프로퍼티에 프록시를 설정하는 방법이 있다. 


아래의 예에서는 HttpURLConnection 을 이용하는 경우에는 Proxy 클래스를 이용하면 간단하게 처리할 수 있다. 


만약 다른 외부 라이브러리를 이용하여 처리하는 경우 해당 라이브러리에 프록시 설정이 없다면

시스템 프로퍼티를 이용하여 처리하면 된다. 

ex) jsoup  


package sdk.java.web;


import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.InetSocketAddress;

import java.net.Proxy;

import java.net.URL;


public class HttpRequest {


public static void main(String[] args) throws Exception {

sendGet();

}

// HTTP GET request

public static void sendGet() throws Exception {


String url = "http://www.naver.com";


// Proxy 클래스 이용

// Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("주소", 포트));

// URL obj = new URL(url);

// HttpURLConnection con = (HttpURLConnection) obj.openConnection(proxy);


// 시스템 프로퍼티 이용 

System.setProperty("http.proxyHost", "주소");

System.setProperty("http.proxyPort", "포트");

URL obj = new URL(url);

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// optional default is GET

con.setRequestMethod("GET");


// add request header

con.setRequestProperty("User-Agent", "Mozilla/5.0");


int responseCode = con.getResponseCode();

System.out.println("\nSending 'GET' request to URL : " + url);

System.out.println("Response Code : " + responseCode);


BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

String inputLine;

StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine).append(System.lineSeparator());

}

in.close();


// print result

System.out.println(response.toString());


}

}




반응형