myPost

package com.xys.java_test.controller.test.xys;

import lombok.extern.slf4j.Slf4j;
import cn.hutool.json.JSONUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
@RequestMapping("/api/test/xys")
public class XysTestController {


    /**
     * url: /api/test/xys/test1
     *
     * @return string
     * @throws Exception 抛出异常
     */
    @PostMapping("test1")
    public String test1() throws Exception {
        return "aaa123123";
    }


    public static void main(String[] args) {
        myPost();
    }

    public static void myPost() {
        String url = "http://localhost:6161/api/test/xys/test2";
        String jsonStr = "";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            // 将JSON作为请求体
            StringEntity entity = new StringEntity(jsonStr, "UTF-8");
            httpPost.setEntity(entity);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new Exception("响应状态码不是200");
                }

                String responseBody = EntityUtils.toString(response.getEntity());
                log.info("响应结果: {}", responseBody);
            }
        } catch (Exception e) {
            log.error("请求失败原因为: " + JSONUtil.toJsonStr(e.getMessage()));
        }
    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容