CloseableHttpResponse 封装的一些基础方法

获取403跳转地址

public static String getAbsUrl(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpClientContext context = HttpClientContext.create();
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        String absUrl = null;
        try {
            response = httpclient.execute(httpget, context);
            HttpHost target = context.getTargetHost();
            List redirectLocations = context.getRedirectLocations();
            URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
//            System.out.println("Final HTTP location: " + location.toASCIIString());
            absUrl = location.toASCIIString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return absUrl;
    }

Http协议Post表单上传

    public static String httpPostForm(String url, Map urls, Map params, Map header, File file, String fileName) throws Exception {
        //初始HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建Post对象
        //写入url
        Set keySet1 = urls.keySet();
        List param = new ArrayList<>();
        for (String key : keySet1) {
            param.add(key + "=" + urls.get(key));
        }
        if (param.size() > 0) {
            url += "?" + String.join("&", param);
        }
        HttpPost httpPost = new HttpPost(url);
        //设置超时
        RequestConfig config = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(20000).build();
        httpPost.setConfig(config);
        //设置header
        Set keySet = header.keySet();
        for (String key : keySet) {
            httpPost.setHeader(key, header.get(key));
        }
        //写入JSON数据
        if (params != null) {
            String json = JSON.toJSONString(params);
            httpPost.setEntity(new StringEntity(json, "UTF-8"));
        }

        //放入文件
        FileBody fileBody = new FileBody(file, ContentType.APPLICATION_OCTET_STREAM);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (fileName == null) {
            builder.addPart("video", fileBody);
        } else {
            builder.addPart(fileName, fileBody);
        }
        HttpEntity fileEntity = builder.build();
        httpPost.setEntity(fileEntity);

        //发起请求,获取response对象
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //获取请求码
        //response.getStatusLine().getStatusCode();
        //获取返回数据实体对象
        HttpEntity entity = response.getEntity();
        //转为字符串
        String result = EntityUtils.toString(entity, "UTF-8");
        return result;
    }

万能post请求

 /**
     * @param url 请求地址 
     * @param urls 路径中的参数 null代表没有
     * @param json 请求体中的参数 null代表没有
     * @param header 请求头中的参数 null代表没有
     * @return
     * @throws Exception
     */
    public static String myHttpPost(String url, Map urls,String json, Map header) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        URIBuilder ub = new URIBuilder(url);
        if (urls != null) {
            urls.forEach((k, v) -> {
                try {
                    ub.addParameter(k, v instanceof String ? (String) v : mapper.writeValueAsString(v));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            });
        }
        URL url1 = ub.build().toURL();

        //初始化HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建Post对象
        HttpPost httpPost = new HttpPost(url1.toString());

        //设置header
        if (header != null) {
            Set keySet = header.keySet();
            for (String key : keySet) {
                httpPost.setHeader(key, header.get(key));
            }
        }
        //写入JSON数据
        if (json != null) {
            httpPost.setEntity(new StringEntity(json,"UTF-8"));
        }
        //发起请求,获取response对象
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //获取请求码
        //response.getStatusLine().getStatusCode();
        //获取返回数据实体对象
        HttpEntity entity = response.getEntity();
        //转为字符串
        String result = EntityUtils.toString(entity, "UTF-8");
        return result;
    }

万能get请求

public static String httpsGet(String url, Map params, Map header) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        URIBuilder ub = new URIBuilder(url);
        if (params != null) {
            params.forEach((k, v) -> {
                try {
                    ub.addParameter(k, v instanceof String ? (String) v : mapper.writeValueAsString(v));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            });
        }
        URL url1 = ub.build().toURL();
        //初始化HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建HttpGet
        HttpGet httpGet = new HttpGet(url1.toString());
        httpGet.addHeader("x-forwarded-for",RandomIp.getRandomIp());
        //设置header
        if (header != null) {
            Set keySet = header.keySet();
            for (String key : keySet) {
                httpGet.setHeader(key, header.get(key));
            }
        }

        //发起请求,获取response对象
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //获取请求状态码

        //获取返回数据实体对象
        HttpEntity entity = response.getEntity();

        //转为字符串
        String result = EntityUtils.toString(entity,"UTF-8");
//        log.info(result);
        return result;
    }

变异get请求(我想将请求的第三方数据直接返给前端)

  //Https协议Get请求带头部信息和参数
    public static void httpsGet(String url, Map params, Map header, HttpServletResponse resp) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        URIBuilder ub = new URIBuilder(url);
        if (params != null) {
            params.forEach((k, v) -> {
                try {
                    ub.addParameter(k, v instanceof String ? (String) v : mapper.writeValueAsString(v));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            });
        }
        URL url1 = ub.build().toURL();
        //初始化HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建HttpGet
        HttpGet httpGet = new HttpGet(url1.toString());
        //设置header
        if (header != null) {
            Set keySet = header.keySet();
            for (String key : keySet) {
                httpGet.setHeader(key, header.get(key));
            }
        }

        //发起请求,获取response对象
        CloseableHttpResponse execute = httpClient.execute(httpGet);
        //获取文件字节流
        byte[] bytes = EntityUtils.toByteArray(execute.getEntity());
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(bytes);
        outputStream.close();
    }

你可能感兴趣的:(json,java,servlet)