java 访问需要有用户名和密码的url,并获取cookie
时间: 2024-01-30 13:01:51 浏览: 145
在 Java 中,可以使用 `HttpURLConnection` 类来访问 URL 并获取 Cookie。以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws IOException {
String username = "your_username";
String password = "your_password";
String urlStr = "http://example.com/login";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String data = "username=" + username + "&password=" + password;
conn.getOutputStream().write(data.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
// process response
}
in.close();
String cookie = conn.getHeaderField("Set-Cookie");
System.out.println("Cookie: " + cookie);
}
}
```
在该示例中,我们首先创建一个 `URL` 对象,并使用 `HttpURLConnection` 打开连接。我们设置请求方法为 `POST`,打开输出流,并将用户名和密码写入输出流中。然后我们读取服务器的响应,并获取返回的 Cookie。
阅读全文