我正在尝试通过一个简单的java桌面应用程序中的OAuth 2.0隐式流程访问Stackexchange API。 我已经通过 URL 获得了non_expiry
acces_token
。
我不喜欢OAuth,到目前为止我尝试的一切都没有让我走得更远。 这是我到目前为止得到的:
private static final String bearerToken = "foobarbaz"; // acces_token
private static void useBearerToken(String bearerToken, String url_str) throws IOException {
BufferedReader reader = null;
URL url = new URL(url_str);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Bearer" + bearerToken);
connection.setDoOutput(true);
connection.setRequestMethod("GET");
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
StringWriter out = new StringWriter(connection.getContentLength() > 0 ? connection.getContentLength() : 2048);
while ((line = reader.readLine()) != null) {
out.append(line);
}
String response = out.toString();
System.out.println(response);
}
public static void main(String[] args) throws IOException {
useBearerToken(bearerToken,"https://api.stackexchange.com/2.2/posts/4308554?site=stackoverflow" );
}
我得到以下异常:
Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
我错过了什么? 我也注册了我的申请。已启用客户端流。我是否必须在某个地方传递我的客户端 ID 或密钥?
我发现异常是由于缺少证书,所以我将更新的 cacerts 文件放在相应的路径:jrelibsecuritycacerts
.
之后,我收到了这个作为对我的请求的回应:
���n�0�_%�!'բH��� ͡� =E!,ĕ��D*�ʪa��K9r�co�w��"�q��yn��Es����Y��z_'b�[2�)T�+��<�h�l=)0z4"�w=��U~c�B��˲�N��w���c��e���(��d�iY���}]>�C��Gs ���s��^��$Ca��ZנW7N���4�}�';0t��r_���N:�ݼ&"t�G;��n��83]�����4�N��^Tu)c�*��û��L�+�����Ս�nj�z��s-��ȣ��K�uh�������/ߟ�N�OϏt3�_�x�Ў�z=����~ǟ��~�8Y�Lj�*� �� dW�%
但是,API 响应是压缩的:
在正常操作期间,我们保证所有响应都被压缩,无论是GZIP还是DEFLATE。
最后,我通过将InputStreamReader
设置为GZIPInputStream
来使其工作:
private static void useBearerToken(String bearerToken, String url_str) throws IOException {
BufferedReader reader = null;
URL url = new URL(url_str);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Bearer" + bearerToken);
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setDoOutput(true);
connection.setRequestMethod("GET");
reader = reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream())));
String line = null;
StringWriter out = new StringWriter(connection.getContentLength() > 0 ? connection.getContentLength() : 2048);
while ((line = reader.readLine()) != null) {
out.append(line);
}
String response = out.toString();
System.out.println(response);
}