首页 > 解决方案 > 如何使用for循环遍历txt文件Java中的行

问题描述

基本上我想做的是在java中做一些东西,将POST请求发送到网站,但每次都有不同的令牌。我有一个充满这些“令牌”的文件,称为 tokens.txt,我希望它为每个请求循环遍历这些文件,以便它为每个令牌发送一个请求。我过去在 python 中做过这样的事情:

link = "https://example.com"
joined = 0
failed = 0
with open("tokens.txt", "r") as f:
    tokens = f.read().splitlines()
    for token in tokens:
        headers = {"Content-Type": "application/json", 
                   "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
                   "Authorization" : token}

        response = post(link, headers=headers).status_code
        if response > 199 and response < 300:
            joined += 1

        else:
            failed += 1

正如您在python代码中看到的那样,它循环通过文件更改令牌变量并发送请求

但是,我对 java 还很陌生,所以我不知道自己在做什么,我很困惑。

标签: javafor-loophttp-post

解决方案


由于您想使用 for 循环,请尝试以下操作:

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        int joined = 0, failed = 0;

        try {

            URL url = new URL("https://example.com");
            Path path = Paths.get("tokens.txt");
            List<String> tokens = Files.readAllLines(path, StandardCharsets.UTF_8);

            for (String token : tokens) {
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11");
                connection.setRequestProperty("Authorization", token);

                int response = connection.getResponseCode();

                if (response > 199 && response < 300)
                    joined++;
                else
                    failed++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

推荐阅读