如何使用for循环遍历Java中的txt文件行。

huangapple go评论72阅读模式
英文:

How to use a for-loop to go through the lines in a txt file Java

问题

基本上我试图做的是用Java制作一个能够向网站发送POST请求的程序,但每次请求时都会使用不同的令牌(token)。我有一个文件,里面充满了这些“令牌”称为tokens.txt,我希望程序能够遍历每个令牌,为每个令牌发送一个请求。过去我在Python中做过类似的事情:

String link = "https://example.com";
int joined = 0;
int failed = 0;

try (BufferedReader br = new BufferedReader(new FileReader("tokens.txt"))) {
    String token;
    while ((token = br.readLine()) != null) {
        String json = ""; // You need to construct your JSON payload here
        
        HttpURLConnection connection = (HttpURLConnection) new URL(link).openConnection();
        connection.setRequestMethod("POST");
        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);
        connection.setDoOutput(true);
        
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = json.getBytes("utf-8");
            os.write(input, 0, input.length);
        }
        
        int response = connection.getResponseCode();
        if (response >= 200 && response < 300) {
            joined++;
        } else {
            failed++;
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

如你在Python代码中所见,这段Java代码会遍历文件并在每次迭代中改变令牌变量,并发送请求。

然而,由于我对Java还比较新,不太清楚我在做什么,感到有些困惑。

英文:

Basically what I am trying to do is make something in java that will send POST requests to a website, but with a different token each time. I have a file full of these "tokens" called tokens.txt and I want it to loop through these for each request so that it sends a request for each token. I have done something like this in the past in python:

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

        response = post(link, headers=headers).status_code
        if response &gt; 199 and response &lt; 300:
            joined += 1

        else:
            failed += 1

As you can see in the python code, It loops through the file changing the token variable and sending the request

However, I am fairly new to java so I don't know what I am doing and I am confused.

答案1

得分: 0

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

    }

}
英文:

Since you want to use a for-loop try this:

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(&quot;https://example.com&quot;);
            Path path = Paths.get(&quot;tokens.txt&quot;);
            List&lt;String&gt; tokens = Files.readAllLines(path, StandardCharsets.UTF_8);

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

                int response = connection.getResponseCode();

                if (response &gt; 199 &amp;&amp; response &lt; 300)
                    joined++;
                else
                    failed++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

huangapple
  • 本文由 发表于 2020年9月19日 04:24:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63962407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定