[Desarrollo empresarial diario] Formas comunes en que Java llama a interfaces http de terceros

Descripción general

En el proceso de desarrollo real, a menudo necesitamos llamar a la interfaz proporcionada por la otra parte o probar si la interfaz que escribimos es adecuada. Muchos proyectos encapsulan y especifican las especificaciones de interfaz de sus propios proyectos, por lo que la mayoría de ellos necesitan llamar a la interfaz proporcionada por la otra parte o a una interfaz de terceros (mensajes de texto, clima, etc.).

Las formas comunes de llamar a interfaces de terceros en proyectos Java son:

  1. A través de clases de red JDKJava.net.HttpURLConnection

  2. Empaquetado a través de Apache comúnHttpClient

  3. Empaquetado a través de ApacheCloseableHttpClient

  4. aprobarOkHttp

  5. vía primaveraRestTemplate

  6. viahutoolHttpUtil

Cómo Java llama a la interfaz http de terceros

A través de la clase de red JDK Java.net.HttpURLConnection

Introducción: solicitudes http proporcionadas por la API nativa de Java en el paquete java.net.

Pasos de uso:

  1. Obtenga el conector (java.net.URLConnection) a través del Localizador uniforme de recursos (java.net.URL).

  2. Establezca los parámetros de la solicitud.

  3. Enviar petición.

  4. Obtenga el contenido devuelto en forma de flujo de entrada.

  5. Cierre el flujo de entrada.

Un método de llamada relativamente primitivo. Aquí coloque la solicitud de obtención y la solicitud de publicación en un método e ingrese el código directamente:

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName: HttpUrlConnectionToInterface
 * @Description: jdk类HttpURLConnection调用第三方http接口
 */
public class HttpUrlConnectionToInterface {
    
    

    /**
     * 以post方式调用对方接口方法
     * @param pathUrl
     */
    public static void doPost(String pathUrl, String data){
    
    
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {
    
    
            URL url = new URL(pathUrl);

            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //设定请求的方法为"POST",默认是GET
            //post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setRequestMethod("POST");

            //设置30秒连接超时
            conn.setConnectTimeout(30000);
            //设置30秒读取超时
            conn.setReadTimeout(30000);

            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            conn.setDoInput(true);

            // Post请求不能使用缓存
            conn.setUseCaches(false);

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
            conn.connect();

            /**
             * 下面的三句代码,就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            //此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用上述的connect()也可以)。
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(data);
            //flush输出流的缓冲
            out.flush();

            /**
             * 下面的代码相当于,获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null){
    
    
                result += str;
            }
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
            conn.disconnect();

        } catch (Exception e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            try {
    
    
                if (out != null){
    
    
                    out.close();
                }
                if (br != null){
    
    
                    br.close();
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    /**
     * 以get方式调用对方接口方法
     * @param pathUrl
     */
    public static void doGet(String pathUrl){
    
    
        BufferedReader br = null;
        String result = "";
        try {
    
    
            URL url = new URL(pathUrl);

            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //设定请求的方法为"GET",默认是GET
            //post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setRequestMethod("GET");

            //设置30秒连接超时
            conn.setConnectTimeout(30000);
            //设置30秒读取超时
            conn.setReadTimeout(30000);

            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            conn.setDoInput(true);

            // Post请求不能使用缓存(get可以不使用)
            conn.setUseCaches(false);

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            //连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
            conn.connect();

            /**
             * 下面的代码相当于,获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String str = "";
            while ((str = br.readLine()) != null){
    
    
                result += str;
            }
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
            conn.disconnect();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            try {
    
    
                if (br != null){
    
    
                    br.close();
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
    
    
        //post请求一般都是把实体对象转为Json字符串
        doGet("https://weather.cma.cn/api/climate?stationid=57516");
    }
}

HttpClient encapsulado a través de apache común

Introducción: El último cliente http hasta el momento es la versión 5.1, la dirección del sitio web oficial: http://hc.apache.org/. El cliente Http está diseñado para promoción y proporciona un fuerte soporte para el protocolo http básico. Aunque el paquete java.net proporciona funciones básicas para el acceso a través de http, no proporciona las funciones requeridas por muchas aplicaciones.

Pasos de uso:

  1. Genere un objeto HttpClient y establezca los parámetros correspondientes;
  2. Genere un objeto GetMethod o PostMethod y establezca los parámetros de respuesta;
  3. Utilice el objeto generado por HttpClient para ejecutar el método Get generado por GetMethod;
  4. Manejar códigos de estado de respuesta;
  5. Si la respuesta es normal, procese el contenido de la respuesta HTTP;
  6. Libere la conexión. Independientemente de si el método de ejecución es exitoso o no, se debe liberar la conexión.
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.1</version>
</dependency>
<!--HttpClient-->
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.IOException;

/**
 * @ClassName: HttpClientToInterface
 * @Description: HttpClient模拟get、post请求并发送请求参数(json等)
 */
public class HttpClientToInterface {
    
    

    /**
     * httpClient的get请求方式
     * 使用GetMethod来访问一个URL对应的网页实现步骤:
     * 1.生成一个HttpClient对象并设置相应的参数;
     * 2.生成一个GetMethod对象并设置响应的参数;
     * 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
     * 4.处理响应状态码;
     * 5.若响应正常,处理HTTP响应内容;
     * 6.释放连接。
     *
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
    
    
        /**
         * 1.生成HttpClient对象并设置参数
         */
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        /**
         * 2.生成GetMethod对象并设置参数
         */
        GetMethod getMethod = new GetMethod(url);
        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        String response = "";

        /**
         * 3.执行HTTP GET 请求
         */
        try {
    
    
            int statusCode = httpClient.executeMethod(getMethod);

            /**
             * 4.判断访问的状态码
             */
            if (statusCode != HttpStatus.SC_OK) {
    
    
                System.err.println("请求出错:" + getMethod.getStatusLine());
            }

            /**
             * 5.处理HTTP响应内容
             */
            //HTTP响应头部信息,这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
            for (Header h : headers) {
    
    
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            //读取HTTP响应内容,这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            //读取为InputStream,在网页内容数据量大时候推荐使用
            //InputStream response = getMethod.getResponseBodyAsStream();

        } catch (HttpException e) {
    
    
            //发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
    
    
            //发生网络异常
            System.out.println("发生网络异常!");
        } finally {
    
    
            /**
             * 6.释放连接
             */
            getMethod.releaseConnection();
        }
        return response;
    }

    /**
     * post请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json) {
    
    
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);

        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        //添加请求参数
        postMethod.addParameter("commentId", json.getString("commentId"));

        String res = "";
        try {
    
    
            int code = httpClient.executeMethod(postMethod);
            if (code == 200) {
    
    
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return res;
    }

    public static void main(String[] args) {
    
    
        doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "UTF-8");
        System.out.println("-----------分割线------------");
        System.out.println("-----------分割线------------");
        System.out.println("-----------分割线------------");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "13026194071");
        doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm", jsonObject);
    }
}

CloseableHttpClient encapsulado por Apache

CloseableHttpClient se modifica y actualiza en función de HttpClient. También implica la configuración del token de encabezado de solicitud (verificación de solicitud). Fastjson se usa para convertir la solicitud o devolver la cadena de resultado al formato json. Por supuesto, los dos métodos anteriores también pueden configurar el encabezado de solicitud. Token y json solo se explican a continuación.

Importe el siguiente paquete jar:

<!--CloseableHttpClient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
</dependency>
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;


/**
 * @ClassName: CloseableHttpClientToInterface
 * @Description: Apache封装好的CloseableHttpClient
 */

public class CloseableHttpClientToInterface {
    
    
    private static String tokenString = "";
    private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";
    private static CloseableHttpClient httpClient = null;

    /**
     * 以get方式调用第三方接口
     *
     * @param url
     * @return
     */
    public static String doGet(String url, String token) {
    
    
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);

        try {
    
    
//            if (tokenString != null && !tokenString.equals("")) {
    
    
//                tokenString = getToken();
//            }
//            //api_gateway_auth_token自定义header头,用于token验证使用
//            get.addHeader("api_gateway_auth_token", tokenString);
            get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            HttpResponse response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    
    
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 以post方式调用第三方接口
     *
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json) {
    
    

        try {
    
    
            if (httpClient == null) {
    
    
                httpClient = HttpClientBuilder.create().build();
            }

            HttpPost post = new HttpPost(url);

            if (tokenString != null && !tokenString.equals("")) {
    
    
                tokenString = getToken();
            }

            //api_gateway_auth_token自定义header头,用于token验证使用
            post.addHeader("api_gateway_auth_token", tokenString);
            post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");

            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/x-www-form-urlencoded");
            //设置请求参数
            post.setEntity(s);
            HttpResponse response = httpClient.execute(post);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    
    
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (httpClient != null) {
    
    
                try {
    
    
                    httpClient.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 获取第三方接口的token
     */
    public static String getToken(){
    
    

        String token = "";

        JSONObject object = new JSONObject();
        object.put("appid", "appid");
        object.put("secretkey", "secretkey");

        try {
    
    
            if (httpClient == null){
    
    
                httpClient = HttpClientBuilder.create().build();
            }
            HttpPost post = new HttpPost("http://localhost/login");

            post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");

            StringEntity s = new StringEntity(object.toString());
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/x-www-form-urlencoded");
            //设置请求参数
            post.setEntity(s);
            HttpResponse response = httpClient.execute(post);

            //这里可以把返回的结果按照自定义的返回数据结果,把string转换成自定义类
            //ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);

            //把response转为jsonObject
            JSONObject result = JSONObject.parseObject(String.valueOf(response));
            if (result.containsKey("token")){
    
    
                token = result.getString("token");
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return token;
    }


    public static void main(String[] args) {
    
    
        System.out.println(doGet("https://weather.cma.cn/api/climate?stationid=57516", null));
    }
}

por OkHttp

Introducción: OkHttp es un cliente HTTP que funciona de forma predeterminada. Realizar HTTP de manera eficiente puede acelerar su carga y ahorrar ancho de banda. Si su servicio tiene varias direcciones IP, OkHttp intentará una dirección alternativa si falla la primera conexión. Esto es necesario para IPv4 + IPv6 y servicios alojados en centros de datos redundantes. OkHttp inicia nuevas conexiones con capacidades TLS modernas (SNI, ALPN) y recurre a TLS 1.0 en caso de falla en el protocolo de enlace. OkHttp es compatible con Android 2.3 y superior. Para Java, el requisito mínimo es 1,7.

Pasos:

  1. Cree OkhttpClient.

  2. mClient ejecuta newCall para convertir la solicitud en una llamada.

  3. Finalmente, la llamada se ejecuta de forma sincrónica y la puesta en cola se ejecuta de forma asincrónica.

  4. La solicitud se crea principalmente a través de Request.Builder.

  5. cache.

  6. Cancelar petición.

Importe el siguiente paquete jar:

<!--okhttp3-->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.1</version>
</dependency>
import okhttp3.*;

import java.io.IOException;

/**
 * @ClassName: OkHttpToInterface
 * @Description: 通过OkHttp调用第三方http接口
 */
public class OkHttpToInterface {
    
    

    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    /**
     * 以get方式调用第三方接口
     *
     * @param url
     */
    public static void doGet(String url) {
    
    
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求,可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
    
    
            @Override
            public void onFailure(Call call, IOException e) {
    
    
                System.out.println("onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
    
    
                System.out.println("onResponse: " + response.body().string());
            }
        });
    }

    /**
     * post请求
     *
     * @param url
     * @param json
     */
    public static void doPost(String url, String json) {
    
    
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        String requestBody = json;
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, requestBody))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
    
    
            @Override
            public void onFailure(Call call, IOException e) {
    
    
                System.out.println("onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
    
    
                System.out.println(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
    
    
                    System.out.println(headers.name(i) + ":" + headers.value(i));
                }
                System.out.println("onResponse: " + response.body().string());
            }
        });
    }

    public static void main(String[] args) {
    
    
//        doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071");
//        doPost("https://api.github.com/markdown/raw", "I am Jdqm.");
        doGet("https://weather.cma.cn/api/climate?stationid=57516");
    }
}

A través de Spring's RestTemplate

RestTemple es la culminación de los primeros tres métodos, lo que facilita la escritura de código. Actualmente, las interfaces de terceros que se pueden utilizar son:

  • eliminar() realiza una operación DELETE HTTP en un recurso en una URL específica
  • exchange()Ejecute un método HTTP específico en la URL y devuelva una ResponseEntity que contenga el objeto asignado desde el cuerpo de la respuesta.
  • execute()Ejecute un método HTTP específico en la URL y devuelva un objeto asignado desde el cuerpo de la respuesta.
  • getForEntity()Envíe una solicitud HTTP GET y la ResponseEntity devuelta contendrá el objeto asignado al cuerpo de la respuesta.
  • getForObject() Envíe una solicitud HTTP GET y el cuerpo de la solicitud devuelta se asignará a un objeto
  • postForEntity()PUBLICAR datos en una URL, devolviendo una ResponseEntity que contiene un objeto asignado desde el cuerpo de la respuesta
  • postForObject() PUBLICAR datos en una URL y devolver un objeto formado en función de la coincidencia del cuerpo de la respuesta
  • headForHeaders() envía una solicitud HTTP HEAD y devuelve el encabezado HTTP que contiene la URL del recurso específico.
  • optionsForAllow() envía una solicitud de OPCIONES HTTP y devuelve la información del encabezado Permitir para una URL específica.
  • postForLocation() PUBLICAR datos en una URL y devolver la URL del recurso recién creado
  • put() PUT recurso a una URL específica

Nota: Actualmente los marcados en rojo son los de uso común.

Pasos:

  1. Utilice el método de construcción predeterminado new una instancia new RestTemplate().

  2. RestTemplate llama internamente al método doExecute para obtener primero ClientHttpRequest.

  3. RestTemplate implementa la clase abstracta HttpAccessor, por lo que se puede llamar a createRequest de la clase principal.

  4. SimpleClientHttpRequestFactory implementa ClientHttpRequest y también implementa métodos.

  5. Siguiente requestCallback.doWithRequest(solicitud)。

  6. Ejecutar respuesta = request.execute().

  7. Finalmente analice la respuesta.

Primero importe el paquete web de springboot

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Clase de configuración

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
 
@Configuration
public class RestTemplateConfig {
    
    
 
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
    
    
        return new RestTemplate(factory);
    }
 
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
    
    
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}
import cn.zysheep.domain.entity.User;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName: RestTemplateToInterface
 * @Description: 通过restTemplate调用第三方http接口
 */
public class RestTemplateToInterface {
    
    
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 以get方式请求第三方http接口 getForEntity
     *
     * @param url
     * @return
     */
    public User doGetWith1(String url) {
    
    
        ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class);
        User user = responseEntity.getBody();
        return user;
    }

    /**
     * 以get方式请求第三方http接口 getForObject
     * 返回值返回的是响应体,省去了我们再去getBody()
     *
     * @param url
     * @return
     */
    public User doGetWith2(String url) {
    
    
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }

    /**
     * 以post方式请求第三方http接口 postForEntity
     *
     * @param url
     * @return
     */
    public String doPostWith1(String url) {
    
    
        User user = new User("小白", 20);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);
        String body = responseEntity.getBody();
        return body;
    }

    /**
     * 以post方式请求第三方http接口 postForEntity
     *
     * @param url
     * @return
     */
    public String doPostWith2(String url) {
    
    
        User user = new User("小白", 20);
        String body = restTemplate.postForObject(url, user, String.class);
        return body;
    }

    /**
     * exchange
     *
     * @return
     */
    public String doExchange(String url, Integer age, String name) {
    
    
        //header参数
        HttpHeaders headers = new HttpHeaders();
        String token = "asdfaf2322";
        headers.add("authorization", token);
        headers.setContentType(MediaType.APPLICATION_JSON);

        //放入body中的json参数
        JSONObject obj = new JSONObject();
        obj.put("age", age);
        obj.put("name", name);

        //组装
        HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
        String body = responseEntity.getBody();
        return body;
    }
}

HttpUtil a través de hutool

Introducción: para obtener información sobre cómo utilizar la clase de herramienta Hutool HttpUtil, consulte el documento oficial Hutool HttpUtil.

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.1</version>
</dependency>
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;

import java.util.HashMap;

/**
 * @ClassName: HttpUtilToInterface
 * @Description: 通过hutool工具类调用第三方http接口
 */
public class HttpUtilToInterface {
    
    
    /**
     * get请求示例
     */
    public static void doGet() {
    
    
        // 最简单的HTTP请求,可以自动通过header等信息判断编码,不区分HTTP和HTTPS
        String result1 = HttpUtil.get("https://www.baidu.com");

        // 当无法识别页面编码的时候,可以自定义请求页面的编码
        String result2 = HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8);

        //可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("city", "北京");
        String result3 = HttpUtil.get("https://www.baidu.com", paramMap);
    }

    public static void main(String[] args) {
    
    
        doGet();
    }

     /**
     * post请求示例
     */
    public static void doPost() {
    
    
        String url = "http://localhost:9001/xss/saveMap";

        //post普通请求示例
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("city", "北京");

        // application/x-www-form-urlencoded
        String result = HttpUtil.post(url, paramMap);
        System.out.println(result);

        // application/json
        String body = HttpUtil.createPost(url).body(JSON.toJSONString(paramMap)).execute().body();
        System.out.println(body);

        //文件上传示例
//        HashMap<String, Object> paramMap1 = new HashMap<>();
//        //文件上传只需将参数中的键指定(默认file),值设为文件对象即可,对于使用者来说,文件上传与普通表单提交并无区别
//        paramMap1.put("file", FileUtil.file("D:\\face.jpg"));
//        String result1 = HttpUtil.post("https://www.baidu.com", paramMap1);
//
//        //下载文件(很少用)
//        String fileUrl = "http://mirrors.sohu.com/centos/8.4.2105/isos/x86_64/CentOS-8.4.2105-x86_64-dvd1.iso";
//        //将文件下载后保存在E盘,返回结果为下载文件大小
//        long size = HttpUtil.downloadFile(fileUrl, FileUtil.file("e:/"));
//        System.out.println("Download size: " + size);
    }

    public static void main(String[] args) {
    
    
        doPost();
    }
}

Resumir

En el desarrollo diario, generalmente utilizamos resttemplate de Spring y HttpUtil de hutool con más frecuencia, especialmente hutool, que es muy recomendable porque contiene muchas herramientas sin preocupaciones.

Supongo que te gusta

Origin blog.csdn.net/qq_45297578/article/details/133036964
Recomendado
Clasificación