java 写一个post方法_个人学习系列 - java代码实现post请求

博主在开发中遇到使用POST请求带参调用其他项目接口的需求,研究后给出Java代码实现。包括搭建Spring Boot环境,如pom.xml配置,还展示了POST和GET方法的测试代码,POST方法通过拼接多参数并设置请求头来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在开发的时候发现了一个需求,就是要使用post请求去请求其他项目的接口,并且还需要带参。所以就研究了一下。

java代码实现post请求

1. 搭建springboot环境

1.1 pom.xml的配置

org.apache.httpcomponents

httpclient

4.5.10

1.2 test POST方法实现

@RunWith(SpringRunner.class)

@SpringBootTest

public class TbFreshScoreInfoEdgeTest {

@Test

public void httpPostRequest(){

//这里根据自己的需要进行数据的填充

String url = "http://IP地址+方法";

HttpClient client = HttpClients.createDefault();

//默认post请求

HttpPost post = new HttpPost(url);

//拼接多参数

JSONObject json = new JSONObject();

json.put("projectId", "1");

json.put("imageName", "2");

json.put("rowId", 3);

json.put("totalVoidArea", 4);

json.put("rowArea", 5);

json.put("voidRadio", 6.0);

json.put("minusScore", 7);

json.put("updateTime", new Date());

String message = "[" + json + "]";

try {

post.addHeader("Content-type", "application/json; charset=utf-8");

post.setHeader("Accept", "application/json");

post.setEntity(new StringEntity(message, StandardCharsets.UTF_8));

HttpResponse httpResponse = client.execute(post);

HttpEntity entity = httpResponse.getEntity();

System.err.println("状态:" + httpResponse.getStatusLine());

System.err.println("参数:" + EntityUtils.toString(entity));

} catch (IOException e1) {

e1.printStackTrace();

}

}

}

1.3 test GET方法实现

public void httpGetRequest() {

String url = "http://IP地址+方法+参数";

try {

HttpClient client = HttpClients.createDefault();

HttpGet httpGet = new HttpGet(url);

BasicResponseHandler responseHandler = new BasicResponseHandler();

System.err.println("参数:" + client.execute(httpGet, responseHandler));

} catch (Exception e) {

e.printStackTrace();

}

}

方法就这些,参考了网上的一些资料。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值