java - 如何使用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 还很陌生,所以我不知道自己在做什么,我很困惑。
解决方案
由于您想使用 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();
}
}
}
推荐阅读
- javascript - 如何在新生成的 div 中正确设置按钮的操作?
- jquery - jQuery动态添加
- git - 如何在 .gitcongfig 命令中管理目录名称中的空格?
- git - Git - 致命:无法打开,致命:克隆后远程端意外挂断
- node.js - 如何停止 Electron windows 共享 cookie?
- python - 以python方式计算两个(或更多!)列表中元素的排列
- g++ - 在 G++ 的 cfg 输出中,“bb”是什么?
- c# - 网格上操作链接的排序列,错误“至少一个对象必须实现 IComparable”
- webpack - 如何在 Webpack 中使用多个进程?
- json - 有没有办法从 JSON 中获取/调用当前工作目录?