簡體   English   中英

如何使用 for 循環遍歷 txt 文件 Java 中的行

[英]How to use a for-loop to go through the lines in a txt file 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 還很陌生,所以我不知道自己在做什么,而且很困惑。

既然你想使用 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();
        }

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM