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

java代码实现post请求

1. 搭建springboot环境

1.1 pom.xml的配置

    <dependency>  
     <groupId>org.apache.httpcomponents</groupId>  
     <artifactId>httpclient</artifactId>  
     <version>4.5.10</version>  
    </dependency>

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();
        }
    }

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


周兆东
107 声望21 粉丝

一个java小白的成长之路。。。