Java # 使用java调用http接口的方法

之前都是使用 ajax 请求接口,现在记录一下使用 java 请求接口的方法

使用 HttpURLConnection

简介:在 java.net 包下,提供访问 HTTP协议 的基本功能类。

1. GET 方式调用

private static void httpURLGETCase() {
    String methodUrl = "请求的http接口地址";
    HttpURLConnection connection = null;
    BufferedReader reader = null;
    String line = null;
    try {
        URL url = new URL(methodUrl + "?name=张三"); // 参数
        // 根据URL生成HttpURLConnection
        connection = (HttpURLConnection) url.openConnection();
        // 默认GET请求
        connection.setRequestMethod("GET");
        // 建立TCP连接
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // 发送http请求
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            // 循环读取流
            while ((line = reader.readLine()) != null) {
                result.append(line).append(System.getProperty("line.separator"));
            }
            String s = result.toString();
            System.out.println(s); // 获取的数据
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.disconnect();
    }
}

 

2. POST方式调用

2.1 带授权的  传递json格式参数调用

private static void httpURLPOSTCase() {
    String methodUrl = "http://xxx";
    HttpURLConnection connection = null;
    OutputStream dataout = null;
    BufferedReader reader = null;
    String line = null;
    try {
        URL url = new URL(methodUrl);
        
        // 根据URL生成HttpURLConnection
        connection = (HttpURLConnection) url.openConnection();
        
        // 设置是否向connection输出,默认false,post请求参数要放在http正文内,需要设为true
        connection.setDoOutput(true);
        
        // 设置是否从connection读入,默认情况下是true;
        connection.setDoInput(true); 
        
        // 设置请求方式为post,默认GET请求
        connection.setRequestMethod("POST");
        
        // post请求不能使用缓存设为false
        connection.setUseCaches(false);
        
        // 连接主机的超时时间
        connection.setConnectTimeout(3000);
        
        // 从主机读取数据的超时时间
        connection.setReadTimeout(3000);
        
        // 设置该HttpURLConnection实例是否自动执行重定向
        connection.setInstanceFollowRedirects(true);
        
        // 连接复用
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Type", "application/json");
        // 授权
        connection.setRequestProperty("Authorization", "Bearer 66cb225f1c3ff0ddfdae31rae2b57488aadfb8b5e7");
        // 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要
        connection.connect();
        
        // 创建输入输出流,用于往连接里面输出携带的参数
        dataout = new DataOutputStream(connection.getOutputStream());
        String body = "[{\"id\":\"44921902\",\"name\":\"张三\"}]";
        dataout.write(body.getBytes());
        dataout.flush();
        dataout.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // 发送http请求
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            // 循环读取流
            while ((line = reader.readLine()) != null) {
                result.append(line).append(System.getProperty("line.separator"));//
            }
            System.out.println(result.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.disconnect();
    }
}

2.2 传递键值对

private static void httpURLPOSTCase() {
    String methodUrl = "http://xxx. ";
    try {
        URL url = new URL(methodUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.connect();

        String body = "userName=zhangsan&password=123456";
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
        writer.write(body);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38134242/article/details/113989053