programing

Java 코드 몇 줄의 문자열에 대한 URL 읽기

sourcetip 2022. 7. 19. 22:52
반응형

Java 코드 몇 줄의 문자열에 대한 URL 읽기

Groovy와 동등한 Java를 찾고 있습니다.

String content = "http://www.google.com".toURL().getText();

URL의 내용을 문자열로 읽고 싶다.그런 간단한 작업을 위해 버퍼링된 스트림과 루프로 코드를 오염시키고 싶지 않습니다.Apache의 HttpClient를 조사했는데도 한두 줄의 구현이 보이지 않습니다.

원래 답변이 받아들여진 후 시간이 좀 지났기 때문에 더 나은 방법이 있습니다.

String out = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A").next();

단일 행이 아닌 약간 완전한 구현을 원하는 경우 다음을 수행합니다.

public static String readStringFromURL(String requestURL) throws IOException
{
    try (Scanner scanner = new Scanner(new URL(requestURL).openStream(),
            StandardCharsets.UTF_8.toString()))
    {
        scanner.useDelimiter("\\A");
        return scanner.hasNext() ? scanner.next() : "";
    }
}

이 답변은 Java의 이전 버전을 참조합니다.당신은 ccleve의 답을 보는 것이 좋을지도 모른다.


이를 위한 기존 방법은 다음과 같습니다.

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static String getText(String url) throws Exception {
        URL website = new URL(url);
        URLConnection connection = website.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                    connection.getInputStream()));

        StringBuilder response = new StringBuilder();
        String inputLine;

        while ((inputLine = in.readLine()) != null) 
            response.append(inputLine);

        in.close();

        return response.toString();
    }

    public static void main(String[] args) throws Exception {
        String content = URLConnectionReader.getText(args[0]);
        System.out.println(content);
    }
}

@extraneon이 제안했듯이 ioutils를 사용하면 Java의 정신에 따라 매우 웅변적인 방법으로 이를 수행할 수 있습니다.

 InputStream in = new URL( "http://jakarta.apache.org" ).openStream();

 try {
   System.out.println( IOUtils.toString( in ) );
 } finally {
   IOUtils.closeQuietly(in);
 }

또는 Apache Commons 또는 인코딩 매개 변수를 사용할 수도 있습니다.

시간이 더 지났기 때문에 Java 8에서 실행하는 방법은 다음과 같습니다.

URLConnection conn = url.openConnection();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
    pageText = reader.lines().collect(Collectors.joining("\n"));
}

Java 9에서는 더 나은 방법이 있습니다.

URL u = new URL("http://www.example.com/");
try (InputStream in = u.openStream()) {
    return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}

원래의 groovy 예시와 같이, 이 예에서는, 컨텐츠가 UTF-8 로 부호화되어 있는 것을 전제로 하고 있습니다.(이것보다 뛰어난 기능이 필요한 경우는, URL Connection을 작성해, 그것을 사용해 부호화를 확인할 필요가 있습니다).

Guava를 사용한 추가 예:

URL xmlData = ...
String data = Resources.toString(xmlData, Charsets.UTF_8);

입력 스트림이 있는 경우(Joe의 답변 참조), ioutils.toString(inputstream)도 검토합니다.

http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString(java.io.InputStream)

다음은 Java 7/8, 안전한 URL 및 요청에 쿠키를 추가하는 방법을 보여 줍니다.이것은 이 페이지의 다른 훌륭한 답변의 대부분 다이렉트 카피입니다만, cookie의 예와 시큐어 URL에서도 동작하는 것에 대한 설명이 추가되었습니다;-)

유효하지 않은 증명서 또는 자체 서명된 증명서를 사용하여 서버에 접속해야 하는 경우 증명서를 Import하지 않는 한 보안 오류가 발생합니다.이 기능이 필요한 경우 StackOverflow에 관한 이 관련 질문에 대한 이 답변에서 상술한 접근방식을 검토할 수 있습니다.

String result = getUrlAsString("https://www.google.com");
System.out.println(result);

출력

<!doctype html><html itemscope="" .... etc

코드

import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public static String getUrlAsString(String url)
{
    try
    {
        URL urlObj = new URL(url);
        URLConnection con = urlObj.openConnection();

        con.setDoOutput(true); // we want the response 
        con.setRequestProperty("Cookie", "myCookie=test123");
        con.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

        StringBuilder response = new StringBuilder();
        String inputLine;

        String newLine = System.getProperty("line.separator");
        while ((inputLine = in.readLine()) != null)
        {
            response.append(inputLine + newLine);
        }

        in.close();

        return response.toString();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}

여기 Jeanne의 멋진 답변이 있습니다. 하지만 저 같은 머펫을 위한 깔끔한 기능으로 포장되어 있습니다.

private static String getUrl(String aUrl) throws MalformedURLException, IOException
{
    String urlData = "";
    URL urlObj = new URL(aUrl);
    URLConnection conn = urlObj.openConnection();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) 
    {
        urlData = reader.lines().collect(Collectors.joining("\n"));
    }
    return urlData;
}

Java 11+:

URI uri = URI.create("http://www.google.com");
HttpRequest request = HttpRequest.newBuilder(uri).build();
String content = HttpClient.newHttpClient().send(request, BodyHandlers.ofString()).body();

순수 Java 문자열 URL

콜 예시

 String str = getStringFromUrl("YourUrl");

실행

답변에서는 URL을 InputStream으로 읽는 방법에 대해 설명하고 이 답변과 InputStream을 String으로 읽는 방법에 대한 답변을 조합할 수 있습니다.

결과는 다음과 같습니다.

public String getStringFromUrl(URL url) throws IOException {
        return inputStreamToString(urlToInputStream(url,null));
}

public String inputStreamToString(InputStream inputStream) throws IOException {
    try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        return result.toString(UTF_8);
    }
}

private InputStream urlToInputStream(URL url, Map<String, String> args) {
    HttpURLConnection con = null;
    InputStream inputStream = null;
    try {
        con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(15000);
        con.setReadTimeout(15000);
        if (args != null) {
            for (Entry<String, String> e : args.entrySet()) {
                con.setRequestProperty(e.getKey(), e.getValue());
            }
        }
        con.connect();
        int responseCode = con.getResponseCode();
        /* By default the connection will follow redirects. The following
         * block is only entered if the implementation of HttpURLConnection
         * does not perform the redirect. The exact behavior depends to 
         * the actual implementation (e.g. sun.net).
         * !!! Attention: This block allows the connection to 
         * switch protocols (e.g. HTTP to HTTPS), which is <b>not</b> 
         * default behavior. See: https://stackoverflow.com/questions/1884230 
         * for more info!!!
         */
        if (responseCode < 400 && responseCode > 299) {
            String redirectUrl = con.getHeaderField("Location");
            try {
                URL newUrl = new URL(redirectUrl);
                return urlToInputStream(newUrl, args);
            } catch (MalformedURLException e) {
                URL newUrl = new URL(url.getProtocol() + "://" + url.getHost() + redirectUrl);
                return urlToInputStream(newUrl, args);
            }
        }
        /*!!!!!*/

        inputStream = con.getInputStream();
        return inputStream;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

장점

  • 순수한 자바입니다.

  • 위의 예시와 같이 늘 오브젝트를 전달하는 대신 다른 헤더를 추가하여 쉽게 확장할 수 있습니다.

  • 프로토콜 스위치 처리가 지원됩니다.

언급URL : https://stackoverflow.com/questions/4328711/read-url-to-string-in-few-lines-of-java-code

반응형