javafx发送http请求
时间: 2023-10-13 21:05:53 浏览: 311
java 发送http和https请求的实例.docx
要使用JavaFX发送HTTP请求,可以使用HttpClient类。以下是一个示例代码:
```java
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequestExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Label responseLabel = new Label("Waiting for response...");
Task<String> task = new Task<String>() {
@Override
protected String call() throws Exception {
return sendHTTPRequest();
}
};
task.setOnSucceeded(event -> {
String response = task.getValue();
responseLabel.setText(response);
});
new Thread(task).start();
VBox root = new VBox(responseLabel);
Scene scene = new Scene(root, 300, 200);
primaryStage.setTitle("HTTP Request Example");
primaryStage.setScene(scene);
primaryStage.show();
}
private String sendHTTPRequest() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
StringBuilder response = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
}
}
```
阅读全文