java修改user-agent_设置随机 User-Agent
时间: 2024-05-25 16:04:56 浏览: 194
可以使用Java的URLConnection类来设置User-Agent,并且可以通过随机生成User-Agent来实现随机化。
以下是一个示例代码:
```java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
private static final List<String> USER_AGENTS = new ArrayList<>();
static {
// 添加一些常见的User-Agent
USER_AGENTS.add("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
USER_AGENTS.add("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586");
USER_AGENTS.add("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246");
}
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", getRandomUserAgent());
connection.connect();
// 处理响应...
}
private static String getRandomUserAgent() {
Random random = new Random();
int index = random.nextInt(USER_AGENTS.size());
return USER_AGENTS.get(index);
}
}
```
在该示例中,我们在静态块中添加了一些常见的User-Agent,然后在获取连接时,随机选择一个User-Agent,并设置到连接的请求头中。这样就可以实现随机化User-Agent了。
阅读全文