catch() 为我的 HTTPs 请求提供"URI is null"



我正试图使用HTTPS请求从这个URI获取JSON对象:"https://api.agify.io/?name=."我希望添加关于我想为哪个名字提取信息的规范,并获得该名字的平均年龄。不幸的是,我似乎无法让它工作,我的catch()正在给uri is null.。看起来我已经尝试过任何东西,所以非常感谢任何帮助。谢谢

package com.fisla.apitest;
import java.util.*;
import java.net.URI;
import java.net.http.HttpRequest;
public class Main {
public static void main(String[] args) {
//Create scanner variable
Scanner in = new Scanner(System.in);
System.out.println("Enter a name:");
String name = in.nextLine();
try {
//Setup newBuilder and specify URI
HttpRequest.newBuilder(new URI("https://api.agify.io/?name=" + name));
//Create the HTTP request and specify its function
HttpRequest request;
request = HttpRequest.newBuilder()
.GET()
.build();
System.out.print(request);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}

你应该这样做

try {
//Create the HTTP request and specify its function
HttpRequest request = HttpRequest
.newBuilder(new URI("https://api.agify.io/?name=" + name));
System.out.print(request);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}

因为当您只执行HttpRequest.newBuilder(new URI("https://api.agify.io/?name=" + name));时,您不会存储对该构建器的任何引用,并且在稍后的示例中,您将创建另一个没有指定URI的构建器。

最新更新