HttpClient远程调用(Spring Boot)

官网:http://hc.apache.org/index.html

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

1 .案例代码

1.1 get请求

public class DoGET {

    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象,相当于打开了浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建HttpGet请求,相当于在浏览器输入地址
        HttpGet httpGet = new HttpGet("http://www.baidu.com/");

        CloseableHttpResponse response = null;
        try {
            // 执行请求,相当于敲完地址后按下回车。获取响应
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应,获取数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                // 关闭资源
                response.close();
            }
            // 关闭浏览器
            httpclient.close();
        }

    }
}

1.2 带参数的get请求

public class DoGETParam {

    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建URI对象,并且设置请求参数
        URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }
}

1.3 POST请求

/*
 * 演示:使用HttpClient发起POST请求
 */
public class DoPOST {
    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http POST请求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/");
        // 把自己伪装成浏览器。否则开源中国会拦截访问
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            // 关闭浏览器
            httpclient.close();
        }

    }
}

1.4 带参数的POST请求

/*
 * 演示:使用HttpClient发起带有参数的POST请求
 */
public class DoPOSTParam {

    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http POST请求,访问开源中国
        HttpPost httpPost = new HttpPost("http://www.oschina.net/search");

        // 根据开源中国的请求需要,设置post请求参数
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        parameters.add(new BasicNameValuePair("scope", "project"));
        parameters.add(new BasicNameValuePair("q", "java"));
        parameters.add(new BasicNameValuePair("fromerr", "8bDnUWwC"));
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应体
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            // 关闭浏览器
            httpclient.close();
        }
    }
}

2.整合项目

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

2.1 在application.properties添加如下配置:

#The config for HttpClient 
http.maxTotal=300
http.defaultMaxPerRoute=50
http.connectTimeout=1000
http.connectionRequestTimeout=500
http.socketTimeout=5000
http.staleConnectionCheckEnabled=true

2.2 config 配置类

package com.czxy.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

/**
 * HttpClient的配置类---类似工具类
 * Configuration:标明这是一个配置类
 * ConfigurationProperties:加载application.properties属性文件
 *          prefix:前缀
 *          ignoreUnknownFields:忽略找不到的属性
 * 自动将属性文件中的值赋值该类中的属性
 *
 * 最终需要知道:
 * 1 SpringBoot推荐使用RestTemplate操作RestFul API
 * 2 RestTemplate底层需要借助HttpClient创建
 *
 *
 */
@Configuration
@ConfigurationProperties(prefix = "http", ignoreUnknownFields = true)
public class HttpClientConfig {

    private Integer maxTotal;// 最大连接

    private Integer defaultMaxPerRoute;// 每个host的最大连接

    private Integer connectTimeout;// 连接超时时间

    private Integer connectionRequestTimeout;// 请求超时时间

    private Integer socketTimeout;// 响应超时时间

    /**
     * HttpClient连接池
     * @return
     */
    @Bean
    public HttpClientConnectionManager httpClientConnectionManager() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(maxTotal);
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        return connectionManager;
    }

    /**
     * 注册RequestConfig
     * @return
     */
    @Bean
    public RequestConfig requestConfig() {
        return RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout)
            .build();
    }

    /**
     * 注册HttpClient
     * @param manager
     * @param config
     * @return
     */
    @Bean
    public HttpClient httpClient(HttpClientConnectionManager manager, RequestConfig config) {
        return HttpClientBuilder.create().setConnectionManager(manager).setDefaultRequestConfig(config)
            .build();
    }
   /**
     * 使用连接池管理连接
     * @param httpClient
     * @return
     */
    @Bean
    public ClientHttpRequestFactory requestFactory(HttpClient httpClient) {
        return new HttpComponentsClientHttpRequestFactory(httpClient);
    }
    /**
     * 使用HttpClient来初始化一个RestTemplate
     * @param requestFactory
     * @return
     */
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) {
        RestTemplate template = new RestTemplate(requestFactory);

        List<HttpMessageConverter<?>> list = template.getMessageConverters();
        for (HttpMessageConverter<?> mc : list) {
            if (mc instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) mc).setDefaultCharset(Charset.forName("UTF-8"));
            }
        }
        return template;
    }

    public Integer getMaxTotal() {
        return maxTotal;
    }

    public void setMaxTotal(Integer maxTotal) {
        this.maxTotal = maxTotal;
    }

    public Integer getDefaultMaxPerRoute() {
        return defaultMaxPerRoute;
    }

    public void setDefaultMaxPerRoute(Integer defaultMaxPerRoute) {
        this.defaultMaxPerRoute = defaultMaxPerRoute;
    }

    public Integer getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(Integer connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public Integer getConnectionRequestTimeout() {
        return connectionRequestTimeout;
    }

    public void setConnectionRequestTimeout(Integer connectionRequestTimeout) {
        this.connectionRequestTimeout = connectionRequestTimeout;
    }

    public Integer getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(Integer socketTimeout) {
        this.socketTimeout = socketTimeout;
    }
}
还有一种写法 借助HttpClient生成RestTemplate,RestTemplate是spring提供的一个远程调用类
package com.czxy.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.web.client.RestTemplate;

/**
 * @author  Fang
 * @create 2018-12-03 20:51
 * @desc httplient config
 **/
@Configuration
@ConfigurationProperties(prefix = "http", ignoreUnknownFields = true)
public class HttpclientConfig {
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

2.3.1 前端页面方法

在这里插入图片描述

在这里插入图片描述

2.3.2 调用(controller)

package com.czxy.web.product;
import com.alibaba.fastjson.JSON;
import com.czxy.pojo.DatagridResult;
import com.czxy.pojo.Product;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Fang
 * @create 2018-10-25 16:20
 * @desc 商品
 **/
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private RestTemplate restTemplate;
   /**
    *@author Fang
    *@create 2018/10/26 21:52
    *@desc  datagrid 分页查询
    **/
    @GetMapping("/findAll")
    public ResponseEntity<DatagridResult> findAll(Integer page, Integer rows) {

        String url = "http://127.0.0.1:8090/product02/findAll02?page=" + page + "&rows=" + rows;

        ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
        String body = entity.getBody();

        DatagridResult datagridResult = JSON.parseObject(body, DatagridResult.class);

        return new ResponseEntity<DatagridResult>(datagridResult, HttpStatus.OK);
    }

    /**
     * @author Fang
     * @create 2018/10/25 18:10
     * @desc 修改
     **/

    @PutMapping("/update")
    public ResponseEntity<Void> update(Product product) {
        String url = "http://127.0.0.1:8090/product02/update02";

        restTemplate.put(url, product);

        return new ResponseEntity(HttpStatus.OK);
    }

  
    /**
    *@author Fang
    *@create 2018/10/25 19:49
    *@desc  删除
    **/
    @DeleteMapping("/deleteProduct/{ids}")
    public ResponseEntity<Void>  delete(@PathVariable("ids") String ids){
        String url="http://127.0.0.1:8090/product02/deleteProduct02/"+ids;
        restTemplate.delete(url);
        return new ResponseEntity(HttpStatus.OK);
    }

}

2.4 接收请求的(controller)

package com.czxy.web.product02;

import com.czxy.pojo.DatagridResult;
import com.czxy.pojo.Product;
import com.czxy.service.product.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;

/**
 * @author Fang
 * @create 2018-10-25 16:20
 * @desc 商品
 **/
@RestController
@RequestMapping("/product02")
public class ProductController02 {

    @Autowired
    private ProductService productService;
  
    /**
    *@author Fang
    *@create 2018/10/26 21:52
    *@desc  datagrid 分页查询
    **/
    @GetMapping("/findAll02")
    public ResponseEntity<DatagridResult> findAll(Integer page, Integer rows) {

        DatagridResult result = productService.findAll(page, rows);

        return new ResponseEntity<DatagridResult>(result, HttpStatus.OK);
    }

    /**
     * @author Fang
     * @create 2018/10/25 18:10
     * @desc 修改
     **/

    @PutMapping("/update02")
    public ResponseEntity<Void> update(@RequestBody Product product) {

        productService.update(product);
        return new ResponseEntity(HttpStatus.OK);
    }


   /**
     *@author Fang
     *@create 2018/10/25 19:49
     *@desc  删除
     **/
    @DeleteMapping("/deleteProduct02/{ids}")
    public ResponseEntity<Void>  delete(@PathVariable("ids") String ids){


        productService.deleteProduct(ids);

        return new ResponseEntity(HttpStatus.OK);
    }



}

3 注意

发送post请求时 接受调用的方法要在参数上加一个@RequestBody注解

如图所示:
在这里插入图片描述

delete请求 注意参数注解

如图所示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值