catch() 给出“URI 为空”对于我的 HTTPs 请求
我正在尝试使用 HTTPS 请求从此 URI 获取 JSON 对象:“https://api.agify.io/?name=”。我希望添加关于我想要提取信息的名称的规范,并获取该名称的平均年龄。不幸的是,我似乎无法让它工作,并且我的 catch()
给出 uri 为 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());
}
}
}
I'm trying to use an HTTPS request to get a JSON object from this URI: "https://api.agify.io/?name=." I hope to add specifications as to which name I'd want to pull information for and get the average age for that name. Unfortunately, I can't seem to get it working and my catch()
is giving uri is null.
Seems like I've tried anything so any help is much appreciated. Thanks!
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());
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你应该这样做
,因为当你只执行
HttpRequest.newBuilder(new URI("https://api.agify.io/?name=" + name));
时,你不会存储任何引用到该构建器,稍后在您的示例中创建另一个没有指定 URI 的构建器。You should do this way
Because when you do just
HttpRequest.newBuilder(new URI("https://api.agify.io/?name=" + name));
you do not store any reference to that builder and later in your example you create another one without URI specified.