【问题标题】:Gmail Oauth2 required accesstoken and refreshtoken using javaGmail Oauth2 需要使用 java 的访问令牌和刷新令牌
【发布时间】:2019-04-11 19:04:04
【问题描述】:

我想创建一个自动发送电子邮件的 java 应用程序,所以我使用 Ouath2,首先我尝试使用我的 clidet id 和 secret id 获取 accesstoken 和 refreshtoken,但我无法获得访问令牌请建议我这。获取accesstoken和refreshtoken在stackoverflow中给出的波纹管代码但对我来说它给出了错误和刷新令牌变量我在代码中留空{params.put("refresh_token","");}我不知道放什么.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONException;
    import org.json.JSONObject;

    /**
     *
     * @author arahman9
     */
    public class Oauth2App {

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws JSONException {
            // TODO code application logic here
           String at =  getAccessToken();
            getAccessToken(at);
        }

        public static String getAccessToken(String refreshToken) throws JSONException {

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
            try {
                String GOOGLE_CLIENT_ID = "xxxxxxxxxxx5lrrb78a44t1lt7moaies.apps.googleusercontent.com";
                String GOOGLE_CLIENT_SECRET = "xxxxxxxx2IZkp6Yi0sRI1";
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
                nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token"));
                nameValuePairs.add(new BasicNameValuePair("client_id", GOOGLE_CLIENT_ID));
                nameValuePairs.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENT_SECRET));
                nameValuePairs.add(new BasicNameValuePair("refresh_token", refreshToken));
                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                org.apache.http.HttpResponse response = client.execute(post);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer buffer = new StringBuffer();
                for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                    buffer.append(line);
                }

                JSONObject json = new JSONObject(buffer.toString());
                String accessToken = json.getString("access_token");
                System.out.println(accessToken);
                return accessToken;

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        public static String getAccessToken() {
            try {
                Map<String, Object> params = new LinkedHashMap<>();
                params.put("grant_type", "refresh_token");
                params.put("client_id","xxxxxxxxxlrrb78a44t1lt7moaies.apps.googleusercontent.com");
            params.put("client_secret","xxxxxxxxIZkp6Yi0sRI1");
            params.put("refresh_token","");

            StringBuilder postData = new StringBuilder();
                for (Map.Entry<String, Object> param : params.entrySet()) {
                    if (postData.length() != 0) {
                        postData.append('&');
                    }
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");

                URL url = new URL("https://accounts.google.com/o/oauth2/token");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setDoOutput(true);
                con.setUseCaches(false);
                con.setRequestMethod("POST");
                con.getOutputStream().write(postDataBytes);

                BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuffer buffer = new StringBuffer();
                for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                    buffer.append(line);
                }

                JSONObject json = new JSONObject(buffer.toString());
                String accessToken = json.getString("access_token");
                return accessToken;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }
    }

错误

run:
java.net.UnknownHostException: accounts.google.com
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:625)
    at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:160)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
    at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:275)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:371)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:933)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1092)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
    at oauth2app.Oauth2App.getAccessToken(Oauth2App.java:98)
    at oauth2app.Oauth2App.main(Oauth2App.java:37)
java.net.UnknownHostException: accounts.google.com
    at java.net.InetAddress.getAllByName0(InetAddress.java:1252)
    at java.net.InetAddress.getAllByName(InetAddress.java:1164)
    at java.net.InetAddress.getAllByName(InetAddress.java:1098)
    at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:263)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:162)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:326)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:610)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:445)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:835)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at oauth2app.Oauth2App.getAccessToken(Oauth2App.java:55)
    at oauth2app.Oauth2App.main(Oauth2App.java:38)
BUILD SUCCESSFUL (total time: 1 second)

新错误

java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/v2/auth
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at oauth2.Oauthmain.getAccessToken(Oauthmain.java:99)
    at oauth2.Oauthmain.main(Oauthmain.java:36)
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at character 1
    at org.json.JSONTokener.syntaxError(JSONTokener.java:413)
    at org.json.JSONObject.<init>(JSONObject.java:180)
    at org.json.JSONObject.<init>(JSONObject.java:420)
    at oauth2.Oauthmain.getAccessToken(Oauthmain.java:61)
    at oauth2.Oauthmain.main(Oauthmain.java:37)

【问题讨论】:

    标签: gmail-api google-oauth refresh-token google-oauth-java-client


    【解决方案1】:

    实际问题出在您的代理上。它适用于您的移动网络。

    新错误 StatusCode->400 表示您发送了错误的请求。您需要以 JSON 的形式发送有效负载。您以错误的格式发送有效负载。在发送之前使用一些 JSON 转换器并将您的数据转换为 JSON。

    StringBuilder postData = new StringBuilder();
                for (Map.Entry<String, Object> param : params.entrySet()) {
                    if (postData.length() != 0) {
                        postData.append('&');
                    }
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");
    

    必须为 JSON 转换器更改该代码


    如果您使用任何代理,请尝试在没有任何代理的情况下连接到另一个网络。


    尝试将授权端点更改为 v2 端点https://accounts.google.com/o/oauth2/v2/auth

    您尝试访问的授权端点是旧端点。所以试试 v2

    【讨论】:

    • 否则我建议使用谷歌Java库进行授权,这样会更简单高效。
    • 是的,我正在我的办公室电脑上尝试
    • 我遇到了同样的错误,所以我将代码复制到我的个人笔记本电脑上,延迟
    • 如果您在代理下,可能是代理问题。只需连接到您的移动网络并尝试
    • 在我的移动网络中,我得到了这样的 Java Native Access (JNA) API Version 4 Version: 4.4.0 (b0) Native: 5.1.0 (74e8f8e397c43487738c5c1f1363498b) Prefix: win32-x86-64
    猜你喜欢
    • 1970-01-01
    • 2021-07-08
    • 2021-12-17
    • 2017-04-14
    • 1970-01-01
    • 2019-09-19
    • 2017-01-18
    • 2019-06-29
    • 1970-01-01
    相关资源
    最近更新 更多