The background,

After a busy week to the happy weekend, and began to grow as a small white journey.

Curl: Call the interface somewhere else, get the data, and do something with it.

So today’s goal is to achieve curl!

Import the core package

The following will be added to pom.xml

< the dependency > < groupId > org, apache httpcomponents < / groupId > < artifactId > httpclient < / artifactId > < version > 4.4 < / version > </dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.51</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>Copy the code

Configure the Properties file

# Maximum number of connections
http.maxTotal = 100
# concurrency
http.defaultMaxPerRoute = 20
The maximum time to create a connection
http.connectTimeout=1000
Get the maximum time to connect from the connection pool
http.connectionRequestTimeout=500
# Maximum time for data transfer
http.socketTimeout=10000
http.validateAfterInactivity=1000
Copy the code

Create the Client entity class

New HttpClientConfiguration. Java

package com.example.demo.controller;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpClientConfiguration {
    @Value("${http.maxTotal}")
    private Integer maxTotal;

    @Value("${http.defaultMaxPerRoute}")
    private Integer defaultMaxPerRoute;

    @Value("${http.connectTimeout}")
    private Integer connectTimeout;

    @Value("${http.connectionRequestTimeout}")
    private Integer connectionRequestTimeout;

    @Value("${http.socketTimeout}")
    private Integer socketTimeout;

    @Value("${http.validateAfterInactivity}")
    private Integer validateAfterInactivity;


    @Bean
    public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(){
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(maxTotal);
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        connectionManager.setValidateAfterInactivity(validateAfterInactivity);
        return connectionManager;
    }

    @Bean
    public HttpClientBuilder httpClientBuilder(PoolingHttpClientConnectionManager poolingHttpClientConnectionManager){
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);

        return httpClientBuilder;
    }

    @Bean
    public CloseableHttpClient closeableHttpClient(HttpClientBuilder httpClientBuilder){
        return httpClientBuilder.build();
    }


    @Bean
    public RequestConfig.Builder builder(){
        RequestConfig.Builder builder = RequestConfig.custom();
        return builder.setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout);
    }

    @Bean
    public RequestConfig requestConfig(RequestConfig.Builder builder){
        returnbuilder.build(); }}Copy the code

New HttpClient. Java

package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class HttpClient {
    public static final String DEFAULT_CHARSET = "UTF-8"; @Autowired private CloseableHttpClient closeableHttpClient; @Autowired private RequestConfig config; /** * API calls in JSON format ** @param url url address * @param requestParameter requestParameter * @param clazz interface return value type * @return
     * @throws Exception
     */
    public <T> T doGet(String url, Map<String, Object> requestParameter, Class<T> clazz) throws Exception {
        String responseJson = this.doGet(url, requestParameter);
        T response = JSONObject.parseObject(responseJson, clazz);
        return response;
    }

    public String doGet(String url, Map<String, Object> requestParameter) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        if(requestParameter ! = null) {for(Map.Entry<String, Object> entry : requestParameter.entrySet()) { uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); }}return this.doGet(uriBuilder.build().toString());
    }

    public String doGet(String url) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(config);
        httpGet.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        CloseableHttpResponse response = this.closeableHttpClient.execute(httpGet);

        int statusCode = response.getStatusLine().getStatusCode();
        if(statusCode ! = HttpStatus.SC_OK) { throw new Exception("api request exception, http reponse code:" + statusCode);
        }

        return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
    }

    public <T> T doPost(String url, Map<String, Object> requestParameter, Class<T> clazz) throws Exception {
        HttpResponse httpResponse = this.doPost(url, requestParameter);
        int statusCode = httpResponse.getCode();
        if(statusCode ! = HttpStatus.SC_OK) { throw new Exception("api request exception, http reponse code:" + statusCode);
        }

        T response = JSONObject.parseObject(httpResponse.getBody(), clazz);
        return response;
    }

    public HttpResponse doPost(String url, Map<String, Object> requestParameter) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(config);
        httpPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());

        if(requestParameter ! = null) { String requestBody = JSONObject.toJSONString(requestParameter); StringEntity postEntity = new StringEntity(requestBody,"UTF-8"); httpPost.setEntity(postEntity); } CloseableHttpResponse response = this.closeableHttpClient.execute(httpPost); // Simply wrap the response to the request into a custom typereturn new HttpResponse(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), DEFAULT_CHARSET));
    }


    public HttpResponse doPost(String url) throws Exception {
        returnthis.doPost(url, null); } /** * public class HttpResponse {/** * HTTP status */ private Integer code; /** * http response content */ private String body; publicHttpResponse() {
        }

        public HttpResponse(Integer code, String body) {
            this.code = code;
            this.body = body;
        }

        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        public String getBody() {
            return body;
        }

        public void setBody(String body) { this.body = body; }}}Copy the code

Do you want to curl up

Curlcontroller.java implements two interfaces, one is the get mode, one is the POST mode.

package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class CurlController {

    @Autowired
    private HttpClient httpClient;

    @RequestMapping("/curlBaidu")
    public String curlBaidu() throws Exception {
        return httpClient.doGet("http://www.baidu.com");
    }

    @RequestMapping("/curlLocation")
    public String curlLocation() throws Exception {

        Map<String, Object> name = new HashMap<>();
        name.put("name"."caohaoyu");
        name.put("name2"."chy");

        HttpClient.HttpResponse httpResult = httpClient.doPost("http://localhost:8080/helloByParam", name);
        String body = httpResult.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);

        return jsonObject.getString("data"); }}Copy the code

Modify the helloByParam interface in the original HelloController.java to receive data from POST and return it directly.

@RequestMapping("/helloByParam")
    public String helloByParam(@RequestBody JSONObject jsonObject) {
        JSONObject result = new JSONObject();
        result.put("msg"."ok");
        result.put("code"."0");
        result.put("data", jsonObject);
        return result.toJSONString();
    }
Copy the code

5. Results

Get implementation result:

Complete the simple curl implementation!

Six, feelings

Java is strongly typed, which is a bit awkward at first for people who are used to writing weak types like PHP. But the editor is still very good to use, later slowly adapt to it.

There is also the Java call method is also more strict, need to pay attention to. You can’t support both POST and GET with PHP’s simple $_REQUEST.

Growth record portal:

Output Hello Word!