programing tip

URL의 InputStream

itbloger 2020. 8. 7. 08:06
반응형

URL의 InputStream


URL에서 InputStream을 얻으려면 어떻게해야합니까?

예를 들어 URL에서 파일을 가져와 wwww.somewebsite.com/a.txt서블릿을 통해 Java의 InputStream으로 읽고 싶습니다 .

난 노력 했어

InputStream is = new FileInputStream("wwww.somewebsite.com/a.txt");

하지만 내가 얻은 것은 오류였습니다.

java.io.FileNotFoundException

java.net.URL#openStream()적절한 URL (프로토콜 포함!)과 함께 사용하십시오 . 예 :

InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();
// ...

또한보십시오:


시험:

final InputStream is = new URL("http://wwww.somewebsite.com/a.txt").openStream();

(a) wwww.somewebsite.com/a.txt는 '파일 URL'이 아닙니다. 전혀 URL이 아닙니다. 당신 http://이 그것의 앞에 붙이면 그것은 분명히 당신이 여기서 의도 한 HTTP URL이 될 것입니다.

(b) FileInputStreamURL이 아닌 파일 용입니다.

(다)에서 입력 스트림을 얻을 수있는 방법 어떤 URL은 경유 URL.openStream(),URL.getConnection().getInputStream(),있는 것과 동일하지만, 당신이 얻을 수있는 다른 이유가있을 수 있습니다 URLConnection처음으로 놀이를.


원본 코드는 파일 시스템 호스팅 파일에 액세스하기위한 FileInputStream을 사용합니다.

사용한 생성자는 현재 작업 디렉터리의 www.somewebsite.com 하위 폴더 (시스템 속성 user.dir의 값)에서 a.txt라는 파일을 찾으려고 시도합니다. 제공 한 이름은 File 클래스를 사용하여 파일로 확인됩니다.

URL 객체는이 문제를 해결하는 일반적인 방법입니다. URL을 사용하여 로컬 파일뿐만 아니라 네트워크 호스팅 리소스에 액세스 할 수 있습니다. URL 클래스는 http : // 또는 https : // 외에 file : // 프로토콜을 지원하므로 계속 사용할 수 있습니다.


순수 자바 :

 urlToInputStream(url,httpHeaders);

약간의 성공으로이 방법을 사용합니다. 그것은 리디렉션을 처리 하고 하나의 변수 번호를 전달할 수 있습니다 HTTP 헤더 등을 Map<String,String>. 또한 HTTP에서 HTTPS 로의 리디렉션을 허용 합니다.

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);
    }
}

전체 예제 호출

private InputStream getInputStreamFromUrl(URL url, String user, String passwd) throws IOException {
        String encoded = Base64.getEncoder().encodeToString((user + ":" + passwd).getBytes(StandardCharsets.UTF_8));
        Map<String,String> httpHeaders=new Map<>();
        httpHeaders.put("Accept", "application/json");
        httpHeaders.put("User-Agent", "myApplication");
        httpHeaders.put("Authorization", "Basic " + encoded);
        return urlToInputStream(url,httpHeaders);
    }

Here is a full example which reads the contents of the given web page. The web page is read from an HTML form. We use standard InputStream classes, but it could be done more easily with JSoup library.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>

</dependency>

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.6</version>
</dependency>  

These are the Maven dependencies. We use Apache Commons library to validate URL strings.

package com.zetcode.web;

import com.zetcode.service.WebPageReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ReadWebPage", urlPatterns = {"/ReadWebPage"})
public class ReadWebpage extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/plain;charset=UTF-8");

        String page = request.getParameter("webpage");

        String content = new WebPageReader().setWebPageName(page).getWebPageContent();

        ServletOutputStream os = response.getOutputStream();
        os.write(content.getBytes(StandardCharsets.UTF_8));
    }
}

The ReadWebPage servlet reads the contents of the given web page and sends it back to the client in plain text format. The task of reading the page is delegated to WebPageReader.

package com.zetcode.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.commons.validator.routines.UrlValidator;

public class WebPageReader {

    private String webpage;
    private String content;

    public WebPageReader setWebPageName(String name) {

        webpage = name;
        return this;
    }

    public String getWebPageContent() {

        try {

            boolean valid = validateUrl(webpage);

            if (!valid) {

                content = "Invalid URL; use http(s)://www.example.com format";
                return content;
            }

            URL url = new URL(webpage);

            try (InputStream is = url.openStream();
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(is, StandardCharsets.UTF_8))) {

                content = br.lines().collect(
                      Collectors.joining(System.lineSeparator()));
            }

        } catch (IOException ex) {

            content = String.format("Cannot read webpage %s", ex);
            Logger.getLogger(WebPageReader.class.getName()).log(Level.SEVERE, null, ex);
        }

        return content;
    }

    private boolean validateUrl(String webpage) {

        UrlValidator urlValidator = new UrlValidator();

        return urlValidator.isValid(webpage);
    }
}

WebPageReader validates the URL and reads the contents of the web page. It returns a string containing the HTML code of the page.

<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <form action="ReadWebPage">

            <label for="page">Enter a web page name:</label>
            <input  type="text" id="page" name="webpage">

            <button type="submit">Submit</button>

        </form>
    </body>
</html>

Finally, this is the home page containing the HTML form. This is taken from my tutorial about this topic.

참고URL : https://stackoverflow.com/questions/6932369/inputstream-from-a-url

반응형