특정 주소를 호출했을 때 xml 등의 결과를 스트링으로 받아오고 싶을 때가 있다. HttpClient를 이용해서 아래와 같은 코드를 사용하면 된다. (HttpClient 다운로드 : http://hc.apache.org/downloads.cgi)
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
String request = "http://192.168.1.10:9090/J2EE/test.xml";
String resultString = "";
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(request);
try {
// Send GET request
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
InputStream rstream = null;
// Get the response body
rstream = method.getResponseBodyAsStream();
// Process the response from Yahoo! Web Services
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) {
resultString += line;
}
br.close();
} catch (Exception e) {
// TODO: handle exception
}