我尝试使用HTTP请求从API获取JSON。但是,我仍然无法设置请求。这是我目前的代码
HttpTransport transport = new HttpTransport() {
@Override
protected LowLevelHttpRequest buildRequest(String s, String s1) throws IOException {
return null;
}
};
我被迫创建一个HTTP传输对象,但我不知道该放入什么内容,文档也没有给我任何线索
@Override
public void action(String[] args, MessageReceivedEvent event) {
HttpRequest request=new HttpRequest(transport,"GET");
request.setUrl(url);
request.setConnectTimeout(5000);
try {
request.execute();
}
catch (IOException e) {
e.printStackTrace();
}
}
url已经包含用于授权的Json Web Token。
但是,在初始化HttpRequest时,它会给我以下错误:
'HttpRequest(com.google.api.client.http.HttpTransport, java.lang.String)' is not public
in 'com.google.api.client.http.HttpRequest'.
Cannot be accessed from outside package
当我清除括号时,甚至会出现此错误:
HttpRequest request=new HttpRequest();
有谁知道,我做错了什么?
更新:我修复了我的代码,但仍然收到错误:
HttpTransport transport = new ApacheHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory();
try {
HttpRequest request = requestFactory.buildGetRequest(url);
request.execute();
System.out.println(request.getContent());
}
catch (IOException e){
e.printStackTrace();
}
我看到的错误是:
avax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
编辑:即使我使用下面的示例,它也会返回此错误
答案 0 :(得分:2)
这意味着HttpRequest
构造函数受到保护以进行调用。您必须使用HttpRequestFactory
工厂来创建HttpRequest
实例。
要获得HttpRequestFactory
,您必须HttpTransport
查看https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/http/HttpTransport
HttpTransport transport = new ApacheHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory();
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse response = request.execute();
try {
// process the HTTP response object
InputStream is = response.getContent();
try {
// Process the input stream..
} finally {
is.close();
}
} finally {
response.disconnect();
}
从未尝试过这个例子,希望它能起作用。