栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Http请求第三方的AccessToken

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Http请求第三方的AccessToken

package com.qw.web_common.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


@Slf4j
@Component
public class Http {
    public String post(String url , String json) throws Exception {
//        BufferedOutputStream  out = null ;
        BufferedReader in = null ;
        StringBuilder sb = new StringBuilder() ;
        try {
            //得到连接对象
            HttpURLConnection connection = getConnection(url);
            //5. 向服务器写入数据
//            out = new BufferedOutputStream(connection.getOutputStream());
//            out.write(json.getBytes());
            //6. 接收服务端的响应
            int responseCode = connection.getResponseCode();
            //7. 响应码为200则读数据
            if (responseCode == 200) {
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                sb = new StringBuilder();
                String temp = null;
                while (null != (temp = in.readLine())) {
                    sb.append(temp);
                }
            }
        }catch(Exception e){
            throw new Exception(e.getMessage());
        }finally{
//            out.close();
            in.close();
        }
        return sb.toString();
    }

        
    private synchronized HttpURLConnection getConnection(String url) throws Exception {
        HttpURLConnection connection = null ;
        try {
            //需要将认证的参数放在地址后面拼接(否则有可能报401)
            url=url+"?grant_type=XXX&client_id=XXX&client_secret=XXX&scope=XXX";
//            1. 创建服务地址
            URL realURL = new URL(url);
            connection = (HttpURLConnection) realURL.openConnection();
            //2. 设置发送方式:POST必须大写
            connection.setRequestMethod("POST");
            //3. 设置数据格式:Content-type
            connection.setRequestProperty("Content-type", "application/json");
            //4. 设置输入,新创建的connection默认是没有写权限的,doOutput值默认为false
            connection.setDoOutput(true);
            return connection;
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new Exception("获取发送地址连接出错");
        }
    }
}

postman方式获取accessToken认证

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/876831.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号