×

httpclient

常用两个工具类,文件下载和httpclient请求,FileDownloadUtil,HttpClientUtil

我的笔记 我的笔记 发表于2020-04-21 17:54:55 浏览3126 评论0

抢沙发发表评论

文件下载工具类:

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description :
 * @Author :付亚东
 * @Date :2019/10/14
 **/
public class FileDownloadUtil {

    /***
     * 根据url保存文件,返回文件路径
     * @param url
     * @param savePath
     * @return
     * @throws Exception
     */
    public static Map download(String url,String savePath,String fileName)throws UnitedException,IOException{
        if(StringUtils.isNotBlank(url)){
            URL con=new URL(url);
            HttpURLConnection conn = (HttpURLConnection) con.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream inputStream = conn.getInputStream();
            byte[] fileByte = readInputstream(inputStream);
            File savePathFile =new File(savePath);
            if(!savePathFile.exists()){
                savePathFile.mkdirs();
            }
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String newName=System.currentTimeMillis()+suffix;
            String filePath = savePath+newName;
            File file=new File(filePath);
            FileOutputStream fileOutputStream=new FileOutputStream(file);
            fileOutputStream.write(fileByte);
            if(fileOutputStream!=null){
                fileOutputStream.close();
            }
            if(inputStream!=null){
                inputStream.close();
            }
            Map map=new HashMap();
            map.put("newName",newName);
            map.put("suffix",suffix);
            map.put("filePath",filePath);
            map.put("file",file);
            return map;

        }else{
            throw new Exception("下载地址不可为空");
        }
    }

    public static byte[] readInputstream(InputStream inputStream) throws IOException{
        int len=0;
        byte[] bytes=new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len=inputStream.read(bytes))!=-1){
            bos.write(bytes,0,len);
        }
        bos.close();
        return bos.toByteArray();
    }

}

httpclient请求工具类:

import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {
    private static final String HTTP = "http";
    private static final String HTTPS = "https";
    private static SSLConnectionSocketFactory sslsf = null;
    private static PoolingHttpClientConnectionManager cm = null;
    private static SSLContextBuilder builder = null;

    public HttpClientUtil() {
    }

    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm).setConnectionManagerShared(true).build();
        return httpClient;
    }

    public static String methodPost(String url, Map<String, String> params, Map<String, String> headers) {
        if (StringUtils.isBlank(url)) {
            return null;
        } else {
            CloseableHttpClient httpclient = getHttpClient();
            HttpResponse response = null;
            HttpPost httpPost = null;
            String result = null;

            try {
                URI uri;
                try {
                    URL url2 = new URL(url);
                    uri = new URI(url2.getProtocol(), url2.getAuthority(), url2.getPath(), url2.getQuery(), (String)null);
                    httpPost = new HttpPost(uri);
                    List<NameValuePair> nvps = new ArrayList();
                    Iterator itor;
                    Entry entry;
                    if (params != null && !params.isEmpty()) {
                        itor = params.entrySet().iterator();

                        while(itor.hasNext()) {
                            entry = (Entry)itor.next();
                            nvps.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
                        }
                    }

                    if (headers != null && !headers.isEmpty()) {
                        itor = headers.entrySet().iterator();

                        while(itor.hasNext()) {
                            entry = (Entry)itor.next();
                            httpPost.addHeader((String)entry.getKey(), (String)entry.getValue());
                        }
                    }

                    try {
                        httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
                    } catch (Exception var28) {
                        entry = null;
                        return entry;
                    }

                    response = httpclient.execute(httpPost);
                    if (response == null) {
                        itor = null;
                        return itor;
                    } else {
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            result = EntityUtils.toString(entity);
                        }

                        return result;
                    }
                } catch (ParseException var29) {
                    
                    uri = null;
                    return uri;
                } catch (IOException var30) {
                    
                    uri = null;
                    return uri;
                } catch (URISyntaxException var31) {
                    
                    uri = null;
                    return uri;
                }
            } finally {
                if (httpclient != null) {
                    try {
                        httpclient.close();
                    } catch (IOException var27) {
                        
                    }
                }

            }
        }
    }

    public static String methodGet(String url, Map<String, String> params, Map<String, String> headers) {
        if (StringUtils.isBlank(url)) {
            return null;
        } else {
            String result = null;
            CloseableHttpClient httpclient = getHttpClient();

            Entry entry;
            try {
                Iterator var6;
                try {
                    if (params != null && !params.isEmpty()) {
                        List<NameValuePair> pairs = new ArrayList(params.size());
                        var6 = params.entrySet().iterator();

                        while(var6.hasNext()) {
                            Entry<String, String> entry = (Entry)var6.next();
                            pairs.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
                        }

                        if (url.indexOf("?") != -1) {
                            url = url + "&" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, "UTF-8"));
                        } else {
                            url = url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, "UTF-8"));
                        }
                    }

                    URL url2 = new URL(url);
                    URI uri = new URI(url2.getProtocol(), url2.getAuthority(), url2.getPath(), url2.getQuery(), (String)null);
                    HttpGet httpget = new HttpGet(uri);
                    if (headers != null && !headers.isEmpty()) {
                        Iterator var8 = headers.entrySet().iterator();

                        while(var8.hasNext()) {
                            entry = (Entry)var8.next();
                            httpget.addHeader((String)entry.getKey(), (String)entry.getValue());
                        }
                    }

                    HttpResponse response = httpclient.execute(httpget);
                    if (response != null) {
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            result = EntityUtils.toString(entity);
                        }

                        return result;
                    }

                    entry = null;
                } catch (Exception var20) {
                    var6 = null;
                    return var6;
                }
            } finally {
                if (httpclient != null) {
                    try {
                        httpclient.close();
                    } catch (IOException var19) {
                    }
                }

            }

            return entry;
        }
    }

    public static String methodGet(String url) {
        if (StringUtils.isBlank(url)) {
            return null;
        } else {
            String result = null;
            CloseableHttpClient httpclient = getHttpClient();

            HttpEntity entity;
            try {
                URL url2 = new URL(url);
                URI uri = new URI(url2.getProtocol(), url2.getAuthority(), url2.getPath(), url2.getQuery(), (String)null);
                HttpGet httpget = new HttpGet(uri);
                HttpResponse response = httpclient.execute(httpget);
                if (response != null) {
                    entity = response.getEntity();
                    if (entity != null) {
                        result = EntityUtils.toString(entity);
                    }

                    return result;
                }

                entity = null;
            } catch (Exception var18) {
                return result;
            } finally {
                if (httpclient != null) {
                    try {
                        httpclient.close();
                    } catch (IOException var17) {
                    }
                }

            }

            return entity;
        }
    }

    public static String methodGet(String url, Map<String, String> headers) {
        if (StringUtils.isBlank(url)) {
            return null;
        } else {
            String result = null;
            CloseableHttpClient httpclient = getHttpClient();

            Entry entry;
            try {
                URI uri;
                try {
                    URL url2 = new URL(url);
                    uri = new URI(url2.getProtocol(), url2.getAuthority(), url2.getPath(), url2.getQuery(), (String)null);
                    HttpGet httpget = new HttpGet(uri);
                    if (headers != null && !headers.isEmpty()) {
                        Iterator var7 = headers.entrySet().iterator();

                        while(var7.hasNext()) {
                            entry = (Entry)var7.next();
                            httpget.addHeader((String)entry.getKey(), (String)entry.getValue());
                        }
                    }

                    HttpResponse response = httpclient.execute(httpget);
                    if (response != null) {
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            result = EntityUtils.toString(entity);
                        }

                        return result;
                    }

                    entry = null;
                } catch (Exception var19) {
                    uri = null;
                    return uri;
                }
            } finally {
                if (httpclient != null) {
                    try {
                        httpclient.close();
                    } catch (IOException var18) {
                    }
                }

            }

            return entry;
        }
    }

    public static JSONObject methodGetJson(String url) {
        String result = methodGet(url);
        return stringToJson(result);
    }

    public static JSONObject stringToJson(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        } else {
            JSONObject jsonObject = null;

            try {
                jsonObject = JSONObject.parseObject(str);
                return jsonObject;
            } catch (Exception var3) {
                return null;
            }
        }
    }

    static {
        try {
            builder = new SSLContextBuilder();
            builder.loadTrustMaterial((KeyStore)null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.create().register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(500);
        } catch (Exception var1) {
        }

    }
}


我的笔记博客版权我的笔记博客版权