UserAgent 的值怎么设置
时间: 2024-04-18 09:28:27 浏览: 76
在Java中,你可以使用`setRequestProperty`方法来设置`User-Agent`头部的值。以下是一个示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
String url = "http://example.com";
String userAgent = "Your User Agent";
try {
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setRequestMethod("GET");
// 设置User-Agent头部信息
connection.setRequestProperty("User-Agent", userAgent);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
} else {
System.out.println("HTTP request failed. Response Code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上述示例中,我们使用`connection.setRequestProperty("User-Agent", userAgent)`来设置`User-Agent`头部的值。你可以将`userAgent`变量替换为你想要设置的具体值。根据需要,你可以添加更多的请求头部信息或者进行其他的修改和扩展。
阅读全文