使用spring的restTemplate方式

  1. 引入依赖
    1
    2
    3
    4
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  2. HttpClient工具类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.client.RestTemplate;
    import java.util.Map;

    @Component
    public class HttpClient {

    @Autowired
    private RestTemplate restTemplate;

    public <T> T doGet(String reqURL,Map<String,Object> params,Class<T> clazz){
    //使用{}占位符,后面跟Object类型参数,这里使用Map<String,String>类型,里面存入了depotId
    T t = restTemplate.getForEntity(reqURL, clazz, params).getBody();
    return t;
    }

    /**
    * doPost响应
    * @param reqURL url链接
    * @param params 入参实体
    * @param clazz 响应实体
    * @return
    */
    public <T> T doPost(String reqURL, Object params, Class<T> clazz){
    T t = restTemplate.postForEntity(reqURL, params, clazz).getBody();
    return t;
    }
    }
  3. RestTemplate配置
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import org.springframework.boot.web.client.RestTemplateBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.client.RestTemplate;

    @Configuration
    public class HttpClientRestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
    }
    }
  4. Controller接口
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import com.smart.Demo.domian.DemoEntity;
    import com.smart.Demo.service.IDemoService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    @Controller
    public class DemoController {
    @Autowired
    IDemoService demoService;

    @ResponseBody
    @GetMapping("/getTest")
    public DemoEntity Test(){
    return demoService.getDemoEntity();
    }
    }
  5. 业务逻辑层接口
    1
    2
    3
    public interface IDemoService {
    DemoEntity getDemoEntity();
    }
  6. 业务逻辑层实现
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    import com.alibaba.fastjson.JSONObject;
    import com.smart.Demo.common.R;
    import com.smart.Demo.domian.DemoEntity;
    import com.smart.Demo.util.HttpClient;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.HashMap;
    import java.util.Map;

    @Service
    public class DemoServiceImpl implements IDemoService{
    @Autowired
    private HttpClient httpClient;
    public String url = "http://blog.renyuxin.cn";

    @Override
    public DemoEntity getDemoEntity() {
    DemoEntity data = new DemoEntity();
    try {
    Map<String, Object> requestMap = new HashMap<>();
    params.put("id", "123456");
    R result = httpClient.doGet(url + "/getSoulSoup?id={id}", params, R.class);
    System.out.println(result.getData());
    // DemoEntity resultData = (DemoEntity) result.getData();
    // 使用阿里的fastjson转格式,根据自己需求转格式
    DemoEntity resultData = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), DemoEntity.class);
    return resultData;
    } catch (Exception e) {
    e.printStackTrace();
    }
    return data;
    }
    }
  7. 实体类
    1
    2
    3
    4
    5
    6
    7
    8
    import lombok.Data;

    @Data
    public class DemoEntity {
    private Integer id;
    private String content;
    private Integer hits;
    }
    输出

    {
    “id”:”1”,
    “content”:”hello world”,
    “hits”:”999”
    }

使用HttpClient方式

  1. maven引入HttpClient依赖
    1
    2
    3
    4
    5
    <!-- httpclient -->
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    </dependency>
  2. HttpClient工具类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;

    import java.io.IOException;

    /**
    * HttpClient工具类
    */
    public class HttpClientUtil {
    /**
    * 发送post请求
    * @param url 请求地址
    * @param data 请求参数
    * @return
    */
    public static String doPost(String url,String data) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    //超时设置
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)
    .setConnectionRequestTimeout(10000) //请求超时
    .setSocketTimeout(10000)
    .setRedirectsEnabled(true) //允许自动重定向
    .build();
    if(url == null) {
    return null;
    }
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(requestConfig);
    httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
    httpPost.setHeader("Accept", "application/json");
    if(data != null && data instanceof String) {
    StringEntity stringEntity = new StringEntity(data,"UTF-8");
    httpPost.setEntity(stringEntity);
    }
    try {
    CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
    if(httpResponse != null) {
    HttpEntity httpEntity = httpResponse.getEntity();
    if(httpEntity != null) {
    String result = EntityUtils.toString(httpEntity);
    return result;
    }
    }
    }catch(Exception e) {
    e.printStackTrace();
    }finally {
    try {
    httpClient.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return null;
    }

    /**
    * 发送get请求
    * @param url 请求地址
    * @return
    */
    public static String goGet(String url){
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
    .setConnectionRequestTimeout(5000)
    .setSocketTimeout(5000)
    .setRedirectsEnabled(true)
    .build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);
    try {
    HttpResponse httpResponse = httpClient.execute(httpGet);
    if(httpResponse.getStatusLine().getStatusCode() == 200) {
    String jsonResult = EntityUtils.toString(httpResponse.getEntity());
    return jsonResult;
    }
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    httpClient.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return null;
    }
    }
  3. 调用工具类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    import com.smart.demo.util.HttpClientUtil;

    public static String getAliJson() {
    String bankId = "6222021608015631234";
    //调用阿里校验银行卡接口
    String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardBinCheck=true&cardNo=";
    String json = HttpClientUtil.goGet(url + bankId);
    return json;
    }
    输出

    {
    “cardType”:”DC”,
    “bank”:”ICBC”,
    “key”:”6222021608015631234”,
    “messages”:[],
    “validated”:true,
    “stat”:”ok”
    }

使用okhttp方式

  1. maven引入okhttp依赖
    1
    2
    3
    4
    5
    6
    7
    <!-- okhttp -->
    <dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.3.1</version>
    <scope>compile</scope>
    </dependency>
  2. 编写okhttp通用类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import java.io.IOException;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;

    public class OkHttp {
    public static String run(String url) throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
    return response.body().string();
    } else {
    throw new IOException("异常 " + response);
    }
    }
    }
  3. 调用okhttp方法
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import java.io.IOException;
    import com.smart.model.util.OkHttp;

    public String getAliJson() {
    try {
    String bankId = "6222021608015631234";
    //调用阿里校验银行卡接口
    String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardBinCheck=true&cardNo=";
    String json = OkHttp.run(url + bankId);
    return json;
    } catch (IOException e) {
    e.printStackTrace();
    return "调用失败";
    }
    }
    输出

    {
    “cardType”:”DC”,
    “bank”:”ICBC”,
    “key”:”6222021608015631234”,
    “messages”:[],
    “validated”:true,
    “stat”:”ok”
    }