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;
/**
* @author qw
* @Description
* @date 9/5/2022
*/
@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认证