Gmail Oauth2需要使用Java的accesstoken和refreshtoken

时间:2018-11-08 09:33:10

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

我想创建一个自动发送电子邮件的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)

1 个答案:

答案 0 :(得分: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