HttpUtils

发布时间 2023-04-06 19:46:57作者: yilan0916

`package com.hikvision.image_display.utils;

import com.alibaba.fastjson2.JSONObject;
import com.google.gson.JsonObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Set;

/**

  • @author zhengkang6

  • @version 1.0

  • @since 2023/3/2
    */
    @Slf4j
    public class HttpUtils {
    private static final String ENCODING = "UTF-8";

    private static final int CONNECT_TIMEOUT = 6000;

    private static final int SOCKET_TIMEOUT = 6000;

    private static final CloseableHttpClient HTTP_CLIENT = HttpClients.createDefault();

    private static final RequestConfig REQUEST_CONFIG = RequestConfig.custom()
    .setConnectTimeout(CONNECT_TIMEOUT)
    .setSocketTimeout(SOCKET_TIMEOUT).build();

    public static CloseableHttpResponse sendPost(String url, Map<String, String> headers, Map<String, String> params) {

     JSONObject jsonObject = new JSONObject(params);
     StringEntity entity = new StringEntity(jsonObject.toString(), Consts.UTF_8);
    
     HttpPost httpPost = new HttpPost(url);
     httpPost.setEntity(entity);
    
     Set<Map.Entry<String, String>> entrySet = headers.entrySet();
     for (Map.Entry<String, String> entry : entrySet) {
         httpPost.setHeader(entry.getKey(), entry.getValue());
     }
    
     CloseableHttpResponse response = null;
     try {
         response = HTTP_CLIENT.execute(httpPost);
     } catch (IOException e) {
         e.printStackTrace();
     }
     return response;
    

    }

    //带body的Get请求
    //https://blog.csdn.net/gusgao/article/details/124250088
    //Apache HttpClient 详解
    //https://juejin.cn/post/7052900785381703694
    //HttpClient 设置用户凭证
    //http://www.yiidian.com/httpclient/httpclient-user-authentication.html

    public static HttpClientResult doGet(String url) {
    return doGet(url, null, null);
    }

    public static HttpClientResult doGet(String url, Map<String, String> params) {
    return doGet(url, null, params);
    }

    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) {

     try {
         URIBuilder uriBuilder = new URIBuilder(url);
         if (params != null) {
             Set<Map.Entry<String, String>> entrySet = params.entrySet();
             for (Map.Entry<String, String> entry : entrySet) {
                 uriBuilder.setParameter(entry.getKey(), entry.getValue());
             }
         }
    
         HttpGet httpGet = new HttpGet(uriBuilder.build());
         httpGet.setConfig(REQUEST_CONFIG);
    
         // 设置请求头
         if (params != null) {
             Set<Map.Entry<String, String>> entrySet = params.entrySet();
             for (Map.Entry<String, String> entry : entrySet) {
                 // 设置到请求头到HttpRequestBase对象中
                 httpGet.setHeader(entry.getKey(), entry.getValue());
             }
         }
    
         // 执行请求
         CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpGet);
    
         // 执行请求并获得响应结果
         if (httpResponse != null && httpResponse.getStatusLine() != null) {
             String content = "";
             if (httpResponse.getEntity() != null) {
                 content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
             }
             return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
         }
     } catch (URISyntaxException e) {
         log.info("URIBuilder出错");
     } catch (IOException e) {
         log.info("HTTP_CLIENT.execute出错");
     }
     return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
    

    }

    public static HttpClientResult doPut(String url) throws URISyntaxException {
    URI serverURI = new URI(url);
    CredentialsProvider credentialsPovider = new BasicCredentialsProvider();
    credentialsPovider.setCredentials(new AuthScope(serverURI.getHost(), serverURI.getPort()),
    new UsernamePasswordCredentials("admin","abcd1234"));

     HttpClientBuilder clientbuilder = HttpClients.custom();
     clientbuilder = clientbuilder.setDefaultCredentialsProvider(credentialsPovider);
    
     CloseableHttpClient httpClient = clientbuilder.build();
    
    
     try {
         URIBuilder uriBuilder = new URIBuilder(url);
    
    
         HttpPut httpPut = new HttpPut(uriBuilder.build());
         httpPut.setConfig(REQUEST_CONFIG);
         httpPut.addHeader("Content-Type", "application/xml");
         String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                 "<SSH version=\"2.0\"\n" +
                 "    xmlns=\"http://www.isapi.org/ver20/XMLSchema\">\n" +
                 "    <enabled>true</enabled>\n" +
                 "</SSH>";
         httpPut.setEntity(new StringEntity(xml, ENCODING));
    
         // 执行请求
         CloseableHttpResponse httpResponse = httpClient.execute(httpPut);
    
         // 执行请求并获得响应结果
         if (httpResponse != null && httpResponse.getStatusLine() != null) {
             String content = "";
             if (httpResponse.getEntity() != null) {
                 content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
             }
             return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
         }
     } catch (URISyntaxException e) {
         log.info("URIBuilder出错");
     } catch (IOException e) {
         log.info("HTTP_CLIENT.execute出错");
     }
     return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
    

    }
    }

`