隐式授权类型 - 如何访问堆栈交换 API

Implicit Grant Type - How to acces the stackexchange API

我正在尝试通过简单的 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=Whosebug" );

}

我得到以下异常:

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文件放到对应的路径:jre\lib\security\cacerts.

之后,我收到了对我请求的回复:

���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 响应是 compressed:

During normal operation, we guarantee that all responses are compressed, either with GZIP or 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);
    
}