SpringBoot项目Post请求各种类型参数传递与调用

        话不多说,直接上代码。

        项目中的各种类型参数接口:

import jhl.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class CodeController {

    // 接收 String 类型参数
    @PostMapping("/testSpring1")
    @ResponseBody
    public String testSpring1(@RequestBody String string){
        System.out.println(string);
        return "return " + string;
    }

    // 可以使用 Map 接收 JSON 格式参数内容
    @PostMapping("/testSpring2")
    @ResponseBody
    public String testSpring2(@RequestBody Map<String, String> map){
        System.out.println("map = " + map);
        return "ok";
    }

    // 可以使用 Java 类对象接收 JSON 格式参数内容
    @PostMapping("/testSpring3")
    @ResponseBody
    public String testSpring3(@RequestBody User user){
        System.out.println("user = " + user);
        return "ok";
    }

    // 接收文件类型参数(图片、文档等)-- 文件上传
    @PostMapping("/testSpring4")
    @ResponseBody
    public String  testSpring4(@RequestParam("file") MultipartFile file){
        String savePath = "D:\\txt"; // 文件保存目录
        String path= savePath + File.separator +file.getOriginalFilename();

        try {
            File destination = new File(path);
            file.transferTo(destination);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "success:" + path;
    }
}

        每种类型参数接口的调用方式:

package jhl.get_request_method;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

public class Code_Test {
    @Test
    public void test1() {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;

        try {
            // 创建 HttpClient 对象
            httpClient = HttpClients.createDefault();

            // 创建 POST 请求
            HttpPost httpPost = new HttpPost("http://localhost:80/test/testSpring1");

            // 设置请求头信息
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept", "application/json");

            // 创建 JSON 请求数据
            String requestBody = "Test information.";
            HttpEntity entity = new StringEntity(requestBody);

            // 设置请求体
            httpPost.setEntity(entity);

            // 发送请求
            response = httpClient.execute(httpPost);

            // 读取响应
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line.trim());
                }

                System.out.println("result.toString() = " + result.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                assert httpClient != null;
                httpClient.close();
            } catch (Exception ee){
                ee.printStackTrace();
            }

            try{
                assert response != null;
                response.close();
            } catch (Exception ee){
                ee.printStackTrace();
            }
        }

    }

    // testSpring2 和 testSpring3的调用方式相同
    @Test
    public void test2(){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;

        try {
            // 创建 HttpClient 对象
            httpClient = HttpClients.createDefault();

            // 创建 POST 请求
            HttpPost httpPost = new HttpPost("http://localhost:80/test/testSpring2");
//            HttpPost httpPost = new HttpPost("http://localhost:80/test/testSpring3");

            // 设置请求头信息
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept", "application/json");

            // 创建 JSON 请求数据
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", "111");
            jsonObject.put("name", "jay");
            jsonObject.put("age", "22");
            String requestBody = jsonObject.toJSONString();
            HttpEntity entity = new StringEntity(requestBody);

            // 设置请求体
            httpPost.setEntity(entity);

            // 发送请求
            response = httpClient.execute(httpPost);

            // 读取响应
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {
                StringBuilder result = new StringBuilder();
                String line = null;
                while ((line = br.readLine()) != null) {
                    result.append(line.trim());
                }

                System.out.println("result.toString() = " + result.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(response!=null){
                try{
                    response.close();
                } catch (Exception ee){
                    ee.printStackTrace();
                }
            }

            if(httpClient!=null){
                try{
                    httpClient.close();
                } catch (Exception ee){
                    ee.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test4(){
        String url = "http://localhost:80/test/testSpring4";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        File file = new File("D:\\txt\\test\\testFile.pdf");

        CloseableHttpResponse response = null;
        HttpPost httppost = new HttpPost(url);
        String name = file.getName();

        try {
            // HttpMultipartMode.RFC6532    避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            builder.setCharset(Consts.UTF_8);
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);
            builder.addBinaryBody("file", Files.readAllBytes(file.toPath()), ContentType.APPLICATION_OCTET_STREAM, name);

            HttpEntity reqEntity = builder.build();
            httppost.setEntity(reqEntity);

            // 设置超时时间
            httppost.setConfig(RequestConfig.
                    custom().
                    setConnectionRequestTimeout(50000).
                    setSocketTimeout(150000).
                    setConnectTimeout(50000).
                    build());
            response = httpClient.execute(httppost);

            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("statusCode = " + statusCode);
            System.out.println("response = " + response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert response != null;
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值