JavaFX进行HTTP Basic认证

最近用JavaFX写一个应用调用Internet上的开放API时需要进行HTTP Basic 认证,JavaFX提供了一个类HttpRequest用于发送Web服务的请求,类HttpHeader顾名思义就是用来表示HTTP请求的"Header"了。HttpHeader提供了一个很方便的方法用来创建HTTP Basic认证需要的用户名和密码"Header":

public  basicAuth(username: java.lang.String, password: java.lang.String) : HttpHeader

下面就看一下如何使用JavaFX编写进行HTTP Basic认证的代码:

//  var user = "user";
//  var password = "password";
HttpRequest{
    location: 
//  url
    headers: HttpHeader.basicAuth(user, password)
    
//  
}.start();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用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(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值