HttClient herramientas

1, dependiente de las importaciones

        <! - httpclient -> 
        < dependencia > 
            < groupId > org.apache.httpcomponents </ groupId > 
            < artifactId > httpclient </ artifactId > 
            < versión > 4.5.3 </ version > 
        </ dependencia > 
        < dependencia > 
            < groupId > org.apache.httpcomponents </ groupId > 
            < artifactId > httpmime </ ArtifactId > 
            <versión > 4.5.3 </ version > 
        </ dependencia > 

        < dependencia > 
            < groupId > commons-codec </ groupId > 
            < artifactId > commons-codec </ artifactId > 
        </ dependencia > 

        < dependencia > 
            < groupId > commons-logging < / groupId > 
            < artifactId > commons-logging </ artifactId > 
            <versión> 1.1.1 </ version > 
        </ dependencia > 
        < dependencia > 
            < groupId > org.apache.httpcomponents </ groupId > 
            < artifactId > httpcore </ artifactId > 
        </ dependencia > 

        <! - GSON工具,封装http用- -> 
        < dependencia > 
            < groupId > com.google.code.gson </ groupId > 
            < artifactId > GSON </ ArtifactId >
            < Versión > 2.8.0 </ version > 
        </ dependencia >
Ver código

2, el paquete get y post

conseguir método devuelve JSON cadena de formato, utilizando el mapa Gson en JSON

net.xdclass.xdvidio.utils empaquetar; 

com.google.gson.Gson importación; 
org.apache.http.HttpEntity importación; 
org.apache.http.HttpResponse importación; 
org.apache.http.client.config.RequestConfig importación; 
org.apache.http.client.methods.CloseableHttpResponse importación; 
org.apache.http.client.methods.HttpGet importación; 
org.apache.http.client.methods.HttpPost importación; 
org.apache.http.entity.StringEntity importación; 
org.apache.http.impl.client.CloseableHttpClient importación; 
org.apache.http.impl.client.HttpClients de importación; 
org.apache.http.util.EntityUtils de importación; 
sun.net.www.http.HttpClient importación; 

java.util.HashMap importación; 
java.util.Map importación; 

/ ** 
 * @author pandas
 * @Date 09/04/2020 22:41 
 * @Version 1.0 
 * @description封装obtener HTTP posterior 
 * / 
public class {HttpUtils 
    estática Mapa < cadena , objeto > mapa = new HashMap <> (); 
    estática final privado GSON Gson = new Gson (); 
    / ** 
     * Obtener 
     * @ param url 
     * @return 
     * / 
    public static Mapa < cadena , objeto > doGet (String url) { 
        CloseableHttpClient HttpClient = HttpClients.createDefault ();  
                .setSocketTimeout (5000)

        RequestConfig requestConfig = RequestConfig.custom (). SetConnectTimeout (5000) //连接超时
                .setConnectionRequestTimeout (5000) //请求超时 
            try {
                .setRedirectsEnabled (true) //允许自动重定向
                .build (); 

        HttpGet HTTPGet = new HttpGet (url); 
        httpGet.setConfig (requestConfig); 
        try { 
           HttpResponse HTTPResponse = httpClient.execute (HTTPGet); 
           si (httpResponse.getStatusLine () getStatusCode () == 200.) { 
               Cadena JsonResult = EntityUtils.toString (httpResponse.getEntity ()); 
               MAP = gson.fromJson (JsonResult, map.getClass ()); 
           } 
        } Catch (Exception e) { 
            e.printStackTrace (); 
        } finally { 
                httpClient.close (); 
            } catch (Exception e) {e.printStackTrace ();} 
        }
        Mapa de retorno; 
    } 

    / ** 
     *封装posterior 
     * @return 
     * / 
    public static cadena doPost (String url, datos String, Integer tiempo de espera) { 
        CloseableHttpClient HttpClient = HttpClients.createDefault (); 

        HttpPost HttpPost = new HttpPost (url); 
        httpPost.addHeader ( "Content-Type", "text / html; chartset = UTF-8"); 

        //设置超时时间
        RequestConfig requestConfig = RequestConfig.custom () setConnectTimeout (timeout) //连接超时. 
                .SetConnectionRequestTimeout (timeout) //请求超时
                .setSocketTimeout (timeout) 
                .setRedirectsEnabled (true) // permite la redirección automática
                .construir(); 
        httpPost.setConfig (requestConfig); 

        si (datos = null &y datos instanceof String) { 
            //使用字符串传参
            StringEntity stringEntry = new StringEntity (datos, "UTF-8"); 
            httpPost.setEntity (stringEntry); 
        } 
        Try { 
            CloseableHttpResponse HTTPResponse = httpClient.execute (HttpPost); 
            HttpEntity httpEntity = httpResponse.getEntity (); 
            si (httpResponse.getStatusLine () getStatusCode () == 200.) { 
                cadena de resultado = EntityUtils.toString (httpEntity); 
                return resultado; 
            } 

        } Catch (Exception e) {e.printStackTrace ();} 
        finally { 
            try { 
                httpClient.close ();
            } catch (Exception e) {e.printStackTrace ();} 

        } 

        return null; 
    } 
}

3, Resumen rutina

1, ejemplos de HttpClient

2, los ejemplos de la solicitud HTTP (HTTPGet / HttpPost / eta)

3, para añadir información a la que solicita

  solicitud de encabezado de solicitud post (addHeader), el cuerpo de la solicitud (setEntity)

  Ejemplos de la requestConfig configuración solicitante, y se cargan en la solicitud, eta

4, HttpClient realiza servidor http solicitudes y vuelve HTTPResponse

  La obtención de la información requerida de HTTPResponse

5, cierre HttpClient.

 

Supongo que te gusta

Origin www.cnblogs.com/jwmdlm/p/12670577.html
Recomendado
Clasificación