android 使用java从网页获取文本[已关闭]

to94eoyn  于 2022-12-28  发布在  Android
关注(0)|答案(1)|浏览(112)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
十小时前关门了。
Improve this question
我试图从一个网页上获取文本使用java我尝试了这段代码,但它是返回空字符串。我想这样做没有任何库。所以请帮助我,我是新的java。

    • 这是密码**
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;

    }

我尝试了BufferedReader,但每次结果都一样。
我尝试了许多代码,但没有为我工作。请解决这个问题或建议我其他方法。

6l7fqoea

6l7fqoea1#

试试这个,很管用。

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

输出版本为0.02

相关问题