简体   繁体   English

使用 java 从网页中获取文本

[英]Fetch Text from webpage using java

I am trying to fetch Text from a webpage using java i tried this code but it is returning empty string.我正在尝试使用 java 从网页中获取文本 我尝试了这段代码,但它返回的是空字符串。 i want do this without any library.我想在没有任何图书馆的情况下这样做。 So help me Please i am new in java.所以请帮助我,我是 java 的新人。

Here is code这是代码

public String checkUpdate(){

        String responseText;

        int responseCode;

        try{

            String urlString = "https://raw.githubusercontent.com/farhanaliofficial/Lite/main/version.txt";

            URL url = new URL(urlString);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");

            connection.setRequestProperty("accept","*/*");

            responseCode = connection.getResponseCode();

            

            Scanner scanner = new Scanner(connection.getInputStream());

            

//          BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            StringBuilder responseBuilder = new StringBuilder();

//          String line;

//

//          while ((line = reader.readLine()) != null) {

//              responseBuilder.append(line);

//          }

//          reader.close();

//          responseText = responseBuilder.toString();

            if(responseCode == 200){

            while (scanner.hasNextLine()) {

                responseBuilder.append(scanner.nextLine());

            }

            responseText = responseBuilder.toString();

            }else{

                responseText = responseCode+"";

            }

        }

        catch(Exception e){

            e.printStackTrace();

            responseText = e.toString();

        }

        return responseText;

    }

I tried BufferedReader but the result is same everytime.我试过BufferedReader但结果每次都一样。

I tried many codes but nothing Works for me.我尝试了很多代码,但没有一个对我有用。 please solve this issue or suggest me other method.请解决这个问题或建议我其他方法。

Try this.试试这个。 It works.有用。

Scanner s = null;
        try {
            s = new Scanner(new URL("https://raw.githubusercontent.com/farhanaliofficial/Lite/main/version.txt").openStream(), "UTF-8").useDelimiter("\\A");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String publicIP = "";
        if (s != null) {
            publicIP = s.next();
        }
        System.out.println("version is " + publicIP);

Output is version is 0.02 Output 是版本是 0.02

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM