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()));
}
}
}
myPost
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 前言 Google Play应用市场对于应用的targetSdkVersion有了更为严格的要求。从 2018 年...