【java】httpclient的使用之java代码内发送http请求

场景:

需要本项目发送HTTP请求到另一个项目中,处理完成返回值给本项目。

1.本项目引入架包

<!-- httpclient  后台发送http请求-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

2.本项目示例代码如下:

【本方法,带着本项目中的UUID去请求了  本地的另一个项目,处理完成之后,获取返回值】

public boolean validate(String uuid){
        CloseableHttpClient closeableHttpClient =  HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet("http://localhost:8080/jms/validate2.jhtml?uuid="+uuid);

        try {
            CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);
            HttpEntity entity = closeableHttpResponse.getEntity();
            String flag = EntityUtils.toString(entity);
            return  "true".equals(flag);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return  false;
    }

3.另一个项目的 示例代码:

【另一个项目中的 这个方法,就是判断本地的一个Vector中是否存在本uuid,如果存在返回true】

@RequestMapping("validate2")
    @ResponseBody
    public boolean validate2(String uuid){
        if(vector.contains(uuid)){
            vector.remove(uuid);
            return true;
        }else{
            return false;
        }
        
    }
原文地址:https://www.cnblogs.com/sxdcgaq8080/p/8311150.html