package com.zc.business.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.HashMap;
//微博获取token的工具类
public class WeiboAuthExample {  
    private static final String APP_KEY = "1894516689";
    private static final String APP_SECRET = "4e89660243b70328fb74ae10f9ed98e5";
    private static final String REDIRECT_URI = "https://api.weibo.com/oauth2/default.html"; // 回调URL,需要URL编码
    private static final String AUTHORIZE_URL = "https://api.weibo.com/oauth2/authorize?client_id="+APP_KEY+"&redirect_uri="+REDIRECT_URI+"&response_type=code";
  
    public static void main(String[] args) throws IOException {  
        // 1. 引导用户到微博授权页面  
        System.out.println("Please visit the following URL to authorize your Weibo account:");  
        System.out.println(AUTHORIZE_URL);  
        System.out.println("After authorization, you will be redirected to the callback URL with an Authorization Code.");  
  
        // 在实际应用中,你应该设置一个HTTP服务器来处理回调,而不是从控制台读取输入。  
        // 这里为了简化示例,我们直接从控制台读取Authorization Code。  
        System.out.print("Enter the Authorization Code from the callback URL: ");  
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));  
        String code = reader.readLine();
        // 2. 使用Authorization Code请求Access Token  
        String accessTokenUrl = "https://api.weibo.com/oauth2/access_token";  
        Map<String, String> params = new HashMap<>();  
        params.put("client_id", APP_KEY);  
        params.put("client_secret", APP_SECRET);  
        params.put("grant_type", "authorization_code");  
        params.put("code", code);  
        params.put("redirect_uri", REDIRECT_URI);  
  
        String accessTokenResponse = sendPostRequest(accessTokenUrl, params);  
        // 解析Access Token响应,实际应用中应该使用JSON库来解析  
        System.out.println("Access Token Response: " + accessTokenResponse);  

    }  
  
    private static String sendPostRequest(String url, Map<String, String> params) throws IOException {  
        URL obj = new URL(url);  
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();  
        con.setRequestMethod("POST");  
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
        con.setRequestProperty("Accept", "application/json");  
        con.setDoOutput(true);  
  
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), StandardCharsets.UTF_8.toString()));
            postData.append('=');
            postData.append(URLEncoder.encode(param.getValue(), StandardCharsets.UTF_8.toString()));
        }
        byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);

        try (OutputStream os = con.getOutputStream()) {
            os.write(postDataBytes);
        }
        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }  
}