用javafx写一个 模拟浏览器get请求范例
时间: 2023-12-13 21:05:54 浏览: 139
当然可以,以下是一个简单的JavaFX模拟浏览器GET请求的范例代码:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class BrowserSimulator extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
VBox root = new VBox();
TextArea responseTextArea = new TextArea();
responseTextArea.setEditable(false);
root.getChildren().add(responseTextArea);
String urlString = "https://www.example.com";
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
responseTextArea.setText(response.toString());
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
运行该应用程序后,它将打开一个窗口,并显示从指定URL获取的响应。
阅读全文