第三节 第三方接口访问:使用java的net库实现http请求

亮子 2023-05-17 03:18:16 10047 0 0 0

1、添加依赖

无需添加依赖

2、示例代码

package com.shenma2009;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 军哥
 * @version 1.0
 * @description: TestHttpNetUrlApp
 * @date 2023/5/17 8:42
 */

public class TestHttpNetUrlApp {
    /**
     * @description GET方法无参请求
     * @author 军哥
     * @date 2023/5/17 8:45
     * @version 1.0
     */
    @Test
    public void  test1() throws IOException {
        URL url = new URL("https://shenmazong.com/test/getRandCode");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }
        String result = response.toString();
        System.out.println(result);
    }

    /**
     * @description GET方法拼接传参
     * @author 军哥
     * @date 2023/5/17 8:45
     * @version 1.0
     */
    @Test
    public void  test2() throws IOException {
        URL url = new URL("https://shenmazong.com/test/getMd5?message=123456");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }
        String result = response.toString();
        System.out.println(result);
    }


    /**
     * @description GET方法发送短信,参数在路径中传递
     * @author 军哥
     * @date 2023/5/17 8:46
     * @version 1.0
     */
    @Test
    public void  test3() throws IOException {
        URL url = new URL("https://www.shenmazong.com/test/sendSms/1/hello");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }
        String result = response.toString();
        System.out.println(result);
    }

    /**
     * @description 通过POST请求传递form表单
     * @author 军哥
     * @date 2023/5/17 11:13
     * @version 1.0
     */
    @Test
    public void  test4() throws IOException {
        URL url = new URL("https://shenmazong.com/test/login?");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        // 准备form表单
        String userName = URLEncoder.encode("andy", "UTF-8");
        String userPass = URLEncoder.encode("123456", "UTF-8");
        String formData = "username="+userName+"&userpass="+userPass;
        System.out.println("formData="+formData);

        connection.setRequestMethod("POST"); //修改请求方法为POST
        connection.setDoOutput(true);
        byte[] postData = formData.getBytes("UTF-8");
        int postDataLength = postData.length;
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.write(postData);
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }
        String result = response.toString();
        System.out.println(result);
    }

    /**
     * @description POST方法传递JSON数据
     * @author 军哥
     * @date 2023/5/17 11:17
     * @version 1.0
     */
    @Test
    public void test8() throws IOException {
        // 创建Map对象并转换为JSON字符串
        Map<String, Object> params = new HashMap<>();
        params.put("userId", "666");
        params.put("message", "hello,world");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(params);
        // 创建连接并设置参数
        URL url = new URL("https://shenmazong.com/test/sendEmail");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);
        // 设置请求体
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(json);
        wr.flush();
        wr.close();
        // 获取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        // 输出响应
        System.out.println(response.toString());
    }

}