import org.apache.commons.codec.binary.Base64; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class ApiRequest { public static void main(String[] args) throws IOException { /** * 资源受限的访问形式:就是get或者post请求必须带着加密后的AccessToken 给服务器才可以访问 * * */ // 1、先解决加密的算命,将加密后的内容先留着 String user = "ADMIN"; String passwd = "KYLIN"; byte[] key = (user + ":" + passwd).getBytes(); String secKey = Base64.encodeBase64String(key); // 2、定义访问路径,通过URL连接的方式将AccessToken 返回给服务端 String urlstr = "http://192.168.253.27:7070/kylin/api/cube_desc/dwd_otc_users_order_cube"; URL url = new URL(urlstr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); //POST也可以通过这种方式请求。 connection.setDoOutput(true); String secKey2 = Base64.encodeBase64String(key); connection.setRequestProperty("Authorization", "Basic " + secKey2); connection.setRequestProperty("Content-Type", "application/json"); // 3、接收返回结果 InputStream inputStream = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; String ss = ""; while ((line = in.readLine()) != null) { ss += line; } System.out.println("查询到的结果是:" + ss); } }
java 带加密的HTTP请求API的访问
最新推荐文章于 2023-10-08 00:01:18 发布