httpclient发送post请求、httpclient上传文件

引入依赖 

        
            org.apache.httpcomponents
            httpclient
            4.5.13
        
        
            org.apache.httpcomponents
            httpmime
            4.5.13
        

1、请求头Content-Type为 application/x-www-form-urlencoded

后端接收方式一:

@RestController
public class PushController {

    @PostMapping("/sendText")
    public String sendText(@RequestParam("groupId") String groupId, @RequestParam("content") String content) {
        System.out.println(groupId);
        System.out.println(content);
        return "ok";
    }
}

或者省略注解@RequestParam

@RestController
public class PushController {

    @PostMapping("/sendText")
    public String sendText(String groupId, String content) {
        System.out.println(groupId);
        System.out.println(content);
        return "ok";
    }
}

 后端接收方式二: 

@RestController
public class PushController {

    @PostMapping("/sendText")
    public String sendText(HttpServletRequest request) {
        String groupId = request.getParameter("groupId");
        String content = request.getParameter("content");
        System.out.println(groupId);
        System.out.println(content);
        return "ok";
    }
}

httpclient客户端发送方式: 


    public static void main(String[] args) {
        try {
            String url = "http://localhost:8080/robot/sendText";
            // 创建 HttpClient 实例
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // 使用 URIBuilder 构建带查询参数的 URL
            URIBuilder uriBuilder = new URIBuilder(url);
            uriBuilder.setParameter("groupId", "379395298");
            uriBuilder.setParameter("content", "测试");

            // 创建 POST 请求实例
            HttpPost httpPost = new HttpPost(uriBuilder.build());
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            // 设置请求配置,包括超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(5000) // 设置 socket 超时时间,单位为毫秒
                    .setConnectTimeout(5000) // 设置连接超时时间,单位为毫秒
                    .build();
            httpPost.setConfig(requestConfig);

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取响应实体
            HttpEntity responseEntity = response.getEntity();
            // 打印响应状态
            System.out.println("响应状态: " + response.getStatusLine().getStatusCode());
            // 如果响应实体不为空,则转换为字符串并打印
            if (responseEntity != null) {
                String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                System.out.println("响应结果: " + responseString);
            }
            // 关闭 HttpClient
            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2、请求头Content-Type为application/json

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);
GET方式无请求体,所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交.

在后端的同一个接收方法里,@RequestBody 与@RequestParam()可以同时使用
@RequestBody最多只能有一个,而@RequestParam()可以有多个。

 后端接收方式一:

@RestController
public class PushController {

    @PostMapping("/sendText")
    public String sendText(@RequestBody Map params) {
        String groupId = (String) params.get("groupId");
        String content = (String) params.get("content");
        System.out.println(groupId);
        System.out.println(content);
        return "ok";
    }
}

 后端接收方式二: 

public class User {
    private String groupId;
    private String content;

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
@RestController
public class PushController {

    @PostMapping("/sendText")
    public String sendText(@RequestBody User user) {
        String groupId = user.getGroupId();
        String content = user.getContent();
        System.out.println(groupId);
        System.out.println(content);
        return "ok";
    }
}

httpclient客户端发送方式: 

    public static void main(String[] args) {
        try {
            String url = "http://localhost:8080/robot/sendText";
            // 创建 HttpClient 实例
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 创建 POST 请求实例
            HttpPost httpPost = new HttpPost(url);

            // 设置请求内容
            HashMap map = new HashMap<>();
            map.put("groupId", "379395298");
            map.put("content", "测试");
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(map);
            StringEntity entity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json");

            // 设置请求配置,包括超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(5000) // 设置 socket 超时时间,单位为毫秒
                    .setConnectTimeout(5000) // 设置连接超时时间,单位为毫秒
                    .build();
            httpPost.setConfig(requestConfig);

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取响应实体
            HttpEntity responseEntity = response.getEntity();
            // 打印响应状态
            System.out.println("响应状态: " + response.getStatusLine().getStatusCode());
            // 如果响应实体不为空,则转换为字符串并打印
            if (responseEntity != null) {
                String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                System.out.println("响应结果: " + responseString);
            }
            // 关闭 HttpClient
            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3、httpclient上传文件

 后端接收方式一:

@RestController
public class PushController {

    @PostMapping("/sendText")
    public String sendText(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        File f = null;
        try {
            if (!file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                int indexOf = fileName.lastIndexOf(".");
                String prefix = fileName.substring(0, indexOf);
                String suffix = fileName.substring(indexOf);
                // 保存文件
                f = new File("/tmp/" + prefix + UUID.randomUUID().toString().replace("-", "") + suffix);
                if (!f.getParentFile().exists()) {
                    f.getParentFile().mkdirs();
                }
                file.transferTo(f.getAbsoluteFile());
                String filePath = f.getAbsolutePath();
                String groupId = request.getParameter("groupId");
                String content = request.getParameter("content");
                System.out.println(filePath);
                System.out.println(groupId);
                System.out.println(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 删除文件
            if (f != null) {
                f.delete();
            }
        }
        return "ok";
    }
}

 httpclient客户端发送方式: 

    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            String url = "http://localhost:8080/robot/sendText";
            String filePath = "F:/test.xlsx";
            // 创建 HttpClient 实例
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 创建 POST 请求实例
            HttpPost httpPost = new HttpPost(url);
            // 创建 MultipartEntityBuilder
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            // 添加文本部分
            builder.addTextBody("groupId", "379395298", ContentType.TEXT_PLAIN.withCharset("UTF-8"));
            builder.addTextBody("content", "测试", ContentType.TEXT_PLAIN.withCharset("UTF-8"));
            // 添加文件部分
            File file = new File(filePath);
            fis = new FileInputStream(file);
            builder.addBinaryBody(
                    "file",
                    fis,
                    ContentType.APPLICATION_OCTET_STREAM,
                    file.getName());
            // 构建 HttpEntity
            HttpEntity multipart = builder.build();
            // 设置 HttpPost 的实体
            httpPost.setEntity(multipart);
            // 设置请求配置,包括超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(5000) // 设置 socket 超时时间,单位为毫秒
                    .setConnectTimeout(5000) // 设置连接超时时间,单位为毫秒
                    .build();
            httpPost.setConfig(requestConfig);

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取响应实体
            HttpEntity responseEntity = response.getEntity();
            // 打印响应状态
            System.out.println("响应状态: " + response.getStatusLine().getStatusCode());
            // 如果响应实体不为空,则转换为字符串并打印
            if (responseEntity != null) {
                String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                System.out.println("响应结果: " + responseString);
            }
            // 关闭 HttpClient
            response.close();
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

你可能感兴趣的:(java,java)