通过HttpClient转发/调用HTTP请求

一、添加依赖

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

二、建立HttpClient . java类

主要代码如下:

@Service
public class HttpClient {
	
	public AjaxResult ajaxResultClient(String url, HttpMethod method, String params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
        //headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setContentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
        HttpEntity<String> requestEntity = new HttpEntity<String>(params, headers);
        //  执行HTTP请求
        ResponseEntity<AjaxResult> response = client.exchange(url, method, requestEntity, AjaxResult.class);
        return response.getBody();
    }
}

三、controller调用示例

 @RequestMapping(value = "/c/save",method= RequestMethod.POST)
    public AjaxResult packing(@RequestBody Map<String,Object> map){
        //api url地址
        String url = "http://127.0.0.1:8088/ml/p/a/save";
        //post请求
        HttpMethod method =HttpMethod.POST;
        Map<String, Object> params= new HashMap<String, Object>();
        params.put("batch", map.get("batch"));
        params.put("num", map.get("num"));
        String paramString =JSON.toJSONString(params);
        //发送http请求并返回结果
        return httpClient.ajaxResultClient(url,method,paramString);
    }
    
    @RequestMapping(value = "/c/a/p/getinfobybatch",method= RequestMethod.GET)
    public AjaxResult getinfobybatch(@RequestParam("batch") String batch){
        //api url地址
        String url = "http://127.0.0.1:8088/m/p/a/getinfobybatch?batch="+batch;
        HttpMethod method =HttpMethod.GET;
        // 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
        Map<String, Object> params= new HashMap<String, Object>();
        String paramString =JSON.toJSONString(params);
        //发送http请求并返回结果
        return httpClient.ajaxResultClient(url,method,paramString);
    }

四、参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值