먼저 고지 사항 : 게시 된 코드 스 니펫은 모두 기본 예입니다. 당신은 사소한 처리해야합니다 IOExceptions와 RuntimeException같은 S NullPointerException, ArrayIndexOutOfBoundsException및 배우자들 자신을.
준비중
먼저 URL과 문자셋을 알아야합니다. 매개 변수는 선택 사항이며 기능 요구 사항에 따라 다릅니다.
String url = "http://example.com";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
// ...
String query = String.format("param1=%s¶m2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
쿼리 매개 변수는 name=value형식 이어야 하고로 연결 해야합니다 &. 일반적 으로을 사용하여 쿼리 매개 변수를 지정된 문자 세트로 URL 인코딩 합니다 URLEncoder#encode().
은 String#format()단지 편의를위한 것입니다. String 연결 연산자 +가 두 번 이상 필요할 때 선호합니다 .
(선택적) 쿼리 매개 변수를 사용 하여 HTTP GET 요청 실행
사소한 일입니다. 기본 요청 방법입니다.
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...
모든 쿼리 문자열은을 사용하여 URL에 연결해야합니다 ?. Accept-Charset당신이 어떤 쿼리 문자열을 전송하지 않는 경우 헤더는.에있는 매개 변수를 인코딩하는 어떤 서버를 암시 할 수 있습니다 당신은 떠날 수 Accept-Charset멀리 헤더를. 헤더를 설정할 필요가 없으면 URL#openStream()바로 가기 방법을 사용할 수도 있습니다 .
InputStream response = new URL(url).openStream();
// ...
다른 쪽이 어느 쪽의 경우는 HttpServlet, 다음의 doGet()방법은 호출 될 상기 파라미터에 의해 가능한 것이다 HttpServletRequest#getParameter().
테스트 목적으로 다음과 같이 응답 본문을 stdout에 인쇄 할 수 있습니다.
try (Scanner scanner = new Scanner(response)) {
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println(responseBody);
}
쿼리 매개 변수를 사용 하여 HTTP POST 요청 실행
로 설정하면 요청 메소드 URLConnection#setDoOutput()가 true내재적으로 POST로 설정됩니다. 웹 양식처럼 표준 HTTP POST application/x-www-form-urlencoded는 쿼리 문자열이 요청 본문에 기록되는 유형 입니다.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
InputStream response = connection.getInputStream();
// ...
참고 : 프로그래밍 방식으로 HTML 양식을 제출할 때마다 요소 name=value쌍을 <input type="hidden">쿼리 문자열로 가져 가야합니다. 물론 프로그래밍 방식으로 "누르고 싶은"요소 name=value쌍 도 잊지 마십시오. <input type="submit">이는 일반적으로 서버 측에서 버튼을 눌렀는지 여부와 구별하는 데 사용됩니다 (있는 경우).
또한 얻어진 캐스트 할 수 있습니다 URLConnection에 HttpURLConnection와를 사용하는 HttpURLConnection#setRequestMethod()대신. 그러나 출력에 연결을 사용하려는 경우 여전히로 설정 URLConnection#setDoOutput()해야 true합니다.
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("POST");
// ...
다른 쪽이 어느 쪽의 경우는 HttpServlet, 다음의 doPost()방법은 호출 될 상기 파라미터에 의해 가능한 것이다 HttpServletRequest#getParameter().
실제로 HTTP 요청을 발생
을 사용하여 HTTP 요청을 명시 적으로 실행할 수 URLConnection#connect()있지만 요청 본문 사용 등의 HTTP 응답에 대한 정보를 얻으려는 경우 요청시 요청이 자동으로 시작 URLConnection#getInputStream()됩니다. 위의 예는 정확히 그렇게하므로 connect()호출은 실제로 불필요합니다.
HTTP 응답 정보 수집
HTTP 응답 상태 :
HttpURLConnection여기 가 필요합니다 . 필요한 경우 먼저 캐스팅하십시오.
int status = httpConnection.getResponseCode();
HTTP 응답 헤더 :
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
HTTP 응답 인코딩 :
Content-Type에 charset매개 변수 가 포함 된 경우 응답 본문은 텍스트를 기반으로하며 서버 측에서 지정한 문자 인코딩으로 응답 본문을 처리하려고합니다.
String contentType = connection.getHeaderField("Content-Type");
String charset = null;
for (String param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charset = param.split("=", 2)[1];
break;
}
}
if (charset != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
for (String line; (line = reader.readLine()) != null;) {
// ... System.out.println(line) ?
}
}
} else {
// It's likely binary content, use InputStream/OutputStream.
}
세션 유지
서버 측 세션은 일반적으로 쿠키에 의해 지원됩니다. 일부 웹 양식은 로그인 및 / 또는 세션에 의해 추적되어야합니다. CookieHandlerAPI를 사용하여 쿠키를 유지 관리 할 수 있습니다 . 당신은 준비 할 필요가 CookieManagerA의 CookiePolicy의를 ACCEPT_ALL모든 HTTP 요청을 보내기 전에.
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
모든 상황에서 항상 제대로 작동하는 것은 아닙니다. 실패하면 쿠키 헤더를 수동으로 수집하고 설정하는 것이 가장 좋습니다. 기본적으로 Set-Cookie로그인 또는 첫 번째 GET요청 의 응답에서 모든 헤더 를 가져 와서 후속 요청을 통해 전달해야합니다.
// Gather all cookies on the first request.
URLConnection connection = new URL(url).openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
// ...
// Then use the same cookies on all subsequent requests.
connection = new URL(url).openConnection();
for (String cookie : cookies) {
connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
// ...
은 split(";", 2)[0]같은 서버 측에 대한 무관 쿠키 속성의 존재를 제거하는 것입니다 expires, path등 또는, 당신은 또한 사용할 수 있습니다 cookie.substring(0, cookie.indexOf(';'))대신 split().
스트리밍 모드
HttpURLConnection기본적으로 의지는 버퍼 전체 실제로 관계없이 사용하여 고정 컨텐츠 길이를 직접 설정 한 여부를 보내기 전에 요청 본문을 connection.setRequestProperty("Content-Length", contentLength);. 이로 인해 OutOfMemoryException많은 POST 요청을 동시에 보낼 때마다 (예 : 파일 업로드) 이 발생할 수 있습니다 . 이를 피하기 위해을 설정하고 싶습니다 HttpURLConnection#setFixedLengthStreamingMode().
httpConnection.setFixedLengthStreamingMode(contentLength);
그러나 콘텐츠 길이를 미리 알 수없는 경우 HttpURLConnection#setChunkedStreamingMode()적절하게 설정하여 청크 스트리밍 모드를 사용할 수 있습니다 . 요청 본문이 청크로 보내질 HTTP Transfer-Encoding헤더를 설정합니다 chunked. 아래 예제는 본문을 1KB 단위로 보냅니다.
httpConnection.setChunkedStreamingMode(1024);
사용자 에이전트
요청이 예상치 못한 응답을 반환하는 반면 실제 웹 브라우저에서는 제대로 작동 할 수 있습니다 . 서버 측이 User-Agent요청 헤더를 기반으로 요청을 차단했을 수 있습니다. URLConnection기본적으로 의지로 설정 Java/1.6.0_19마지막 부분은 분명히 JRE 버전입니다. 다음과 같이이를 재정의 할 수 있습니다.
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7.
최신 브라우저 에서 User-Agent 문자열을 사용하십시오 .
오류 처리
HTTP 응답 코드가 4nn(클라이언트 오류) 또는 5nn(서버 오류) 인 HttpURLConnection#getErrorStream()경우 서버에서 유용한 오류 정보를 보냈는지 확인하십시오.
InputStream error = ((HttpURLConnection) connection).getErrorStream();
HTTP 응답 코드가 -1이면 연결 및 응답 처리에 문제가 있습니다. HttpURLConnection구현은 이전의 JRE에 연결을 유지 하느라 다소 버그가 있습니다. http.keepAlive시스템 속성을 로 설정하여 끌 수 있습니다 false. 응용 프로그램을 시작할 때 다음과 같이 프로그래밍 방식으로이 작업을 수행 할 수 있습니다.
System.setProperty("http.keepAlive", "false");
파일 업로드
일반적으로 multipart/form-data혼합 POST 컨텐츠 (이진 및 문자 데이터)에 인코딩을 사용 합니다. 인코딩은 RFC2388 에 더 자세히 설명되어 있습니다 .
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
// Send text file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
}
다른 측면이 경우 HttpServlet, 다음의 doPost()메소드가 호출되고 부품으로 사용할 수 있습니다 HttpServletRequest#getPart()(참고, 이렇게 하지 getParameter() 등등!). getPart()방법은 비교적 새로운 그러나, 이것은 서블릿 3.0 (3 글래스 피시 톰캣 7 등)에 도입되는 것. Servlet 3.0 이전에는 Apache Commons FileUpload 를 사용하여 multipart/form-data요청 을 구문 분석하는 것이 가장 좋습니다 . FileUpload 및 Servelt 3.0 접근 방식의 예제 도이 답변 을 참조하십시오 .
신뢰할 수 없거나 잘못 구성된 HTTPS 사이트 다루기
때로는 웹 스크레이퍼를 작성하고 있기 때문에 HTTPS URL을 연결해야 할 수도 있습니다. 이 경우 javax.net.ssl.SSLException: Not trusted server certificateSSL 인증서를 최신 상태로 유지하지 않는 일부 HTTPS 사이트 java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found또는 javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name잘못 구성된 일부 HTTPS 사이트에서 문제가 발생할 수 있습니다.
static웹 스크래퍼 클래스에서 다음의 1 회 실행 초기화 프로그램은 HttpsURLConnection해당 HTTPS 사이트에 대해 보다 관대 해져 더 이상 예외를 발생시키지 않아야합니다.
static {
TrustManager[] trustAllCertificates = new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null; // Not relevant.
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// Do nothing. Just allow them all.
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// Do nothing. Just allow them all.
}
}
};
HostnameVerifier trustAllHostnames = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true; // Just allow them all.
}
};
try {
System.setProperty("jsse.enableSNIExtension", "false");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCertificates, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
}
catch (GeneralSecurityException e) {
throw new ExceptionInInitializerError(e);
}
}
마지막 말
아파치 HttpComponents HttpClient를이 입니다 훨씬 더 편리이 모두 :)
HTML 파싱 및 추출
HTML에서 데이터를 구문 분석하고 추출하는 것만 있으면 Jsoup 과 같은 HTML 파서를 사용하는 것이 좋습니다.