HttpURLConnection中请求头中携带Token的使用方法

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class TokenRequestExample {
    
    

    public static void main(String[] args) throws IOException {
    
    
        // 设置API地址
        String apiUrl = "
        
        // 设置Token
        String token = "your_token_here";
        // 创建URL对象
        URL url = new URL(apiUrl);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置请求头中的Authorization字段
        connection.setRequestProperty("Authorization", "Bearer " + token);
        
        // 发送GET请求
        connection.setRequestMethod("GET");
        // 获取响应结果
        int responseCode = connection.getResponseCode();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
    
    
            response.append(line);
        }
        reader.close();

        // 处理响应结果
        if (responseCode == HttpURLConnection.HTTP_OK) {
    
    
            System.out.println("请求成功!");
            System.out.println("响应内容:" + response.toString());
        } else {
    
    
            System.out.println("请求失败!");
            System.out.println("响应代码:" + responseCode);
            System.out.println("响应内容:" + response.toString());
        }

        // 关闭连接
        connection.disconnect();
    }
}

import java.net.HttpURLConnection;

/**
 * HttpGet请求
 * @param vurl:请求地址,map:{头部信息}
 * @return 返回消息
 */
public static String httpGet(String vurl,HashMap<String, Object> map) {
    
    
    try {
    
    
        URL url = new URL(vurl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        for (Map.Entry item : map.entrySet()) {
    
    
            connection.setRequestProperty(item.getKey().toString(),item.getValue().toString());//设置header
        }
        InputStream in = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(in, "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
    
    
            sb.append(line);
        }
        br.close();
        isr.close();
        in.close();
        return sb.toString();
    } catch (IOException e) {
    
    
        e.printStackTrace();
        return null;
    }
}

一般会在头部添加认证信息,如token值或BasicAuth认证的 Authorization值

HashMap<String, Object> tmap = new HashMap<String, Object>();
tmap.put("Authorization",authorization);//tmap.put("token","tonken值");
String vmsg= Comm.httpGet(vurl,tmap);//获取请求的返回结果

猜你喜欢

转载自blog.csdn.net/ximaiyao1984/article/details/132426671
今日推荐