java通过http请求调用接口 (get ,post,上传文件)

假如想象 提交于 2020-04-07 15:16:48
package com.xx.util;

import com.alibaba.fastjson.JSON;
import com.hcr.aurora.vo.ParamVo1;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    public String post(List<NameValuePair> params, String url, ENCODING_CONSTANT encoding) throws IOException {

        System.out.println(url);
        CloseableHttpClient httpclient = getHttpClient();

        HttpPost httppost = new HttpPost(url);
        //加 authorization
        httppost.addHeader("authorization", Base64Util.getAuthorizationValue(getType(url)));
        httppost.setHeader("Content-Type", "application/json");
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(100000).setConnectionRequestTimeout(100000)
                .setSocketTimeout(100000).build();
        httppost.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String s = "";
        try {
            httppost.setEntity(new UrlEncodedFormEntity(params, encoding.getRequest_encoding()));
            response = httpclient.execute(httppost);
            entity = response.getEntity();
            s = EntityUtils.toString(entity, encoding.getEncoding());
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            closeHttpClient(httpclient);
        }
        return s;
    }

    public String get(String url, ENCODING_CONSTANT encoding) throws IOException {
        System.out.println(url);
        long startTime=System.currentTimeMillis();
        CloseableHttpClient httpclient = getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        System.out.println(Base64Util.getAuthorizationValue(getType(url)));
        httpGet.setHeader("authorization", Base64Util.getAuthorizationValue(getType(url)));

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(100000).setConnectionRequestTimeout(100000)
                .setSocketTimeout(100000).build();
        httpGet.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String s = "";
        try {
            response = httpclient.execute(httpGet);
            entity = response.getEntity();
            s = EntityUtils.toString(entity, encoding.getEncoding());
            System.out.println(s);
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {

            e1.printStackTrace();
            Connection con = Jsoup.connect(url);
            Document doc = con.ignoreContentType(true).timeout(100000).get();
            s = doc.body().text();
        } finally {
            closeHttpClient(httpclient);
        }
        long endTime=System.currentTimeMillis();
        System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
        return s;
    }

    public  String getWithHeader(String url, ENCODING_CONSTANT encoding, Map<String, String> header) throws IOException {
        System.out.println(url);
        CloseableHttpClient httpclient = getHttpClient();

        HttpGet httpGet = new HttpGet(url);
        for(String key : header.keySet()){
            httpGet.setHeader(key, header.get(key));
        }
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(100000).setConnectionRequestTimeout(100000)
                .setSocketTimeout(100000).build();
        httpGet.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String s = "";
        try {
            response = httpclient.execute(httpGet);
            entity = response.getEntity();
            s = EntityUtils.toString(entity, encoding.getEncoding());
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {

            e1.printStackTrace();
            Connection con = Jsoup.connect(url);
            Document doc = con.ignoreContentType(true).timeout(100000).get();
            s = doc.body().text();
        } finally {
            closeHttpClient(httpclient);
        }
        return s;
    }

    public  String getWithHeader2(String url, ENCODING_CONSTANT encoding, Map<String, String> header) throws IOException {
        System.out.println(url);

        CloseableHttpClient httpclient = getHttpClient();
//        params=URLEncoder.encode(params,encoding.getEncoding());
//        System.out.println(url+params);
        HttpGet httpGet = new HttpGet(url);
        for(String key : header.keySet()){
            httpGet.setHeader(key, header.get(key));
        }
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(100000).setConnectionRequestTimeout(100000)
                .setSocketTimeout(100000).build();
        httpGet.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String s = "";
        try {
            response = httpclient.execute(httpGet);
            entity = response.getEntity();
            s = EntityUtils.toString(entity, encoding.getEncoding());
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {

            e1.printStackTrace();
            Connection con = Jsoup.connect(url);
            Document doc = con.ignoreContentType(true).timeout(100000).get();
            s = doc.body().text();
        } finally {
            closeHttpClient(httpclient);
        }
        return s;
    }

    private CloseableHttpClient getHttpClient() {
        return HttpClients.createDefault();
    }

    private void closeHttpClient(CloseableHttpClient client) throws IOException {
        if (client != null) {
            client.close();
        }
    }

    public String post2(String params, String url, ENCODING_CONSTANT encoding) throws IOException {

        System.out.println(url);
        CloseableHttpClient httpclient = getHttpClient();
        BufferedReader in = null;
        CloseableHttpResponse response= null;
        String s ="";
        try{

            HttpPost httppost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(100000).setConnectionRequestTimeout(100000)
                    .setSocketTimeout(100000).build();
            httppost.setConfig(requestConfig);
            System.out.println(Base64Util.getAuthorizationValue(getType(url)));
            httppost.addHeader("authorization", Base64Util.getAuthorizationValue(getType(url)));
            httppost.setHeader("Content-Type", "application/json");
//            httppost.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
//            httppost.setHeader("Accept", "application/json");
            httppost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
            response = httpclient.execute(httppost);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            s = sb.toString();
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                closeHttpClient(httpclient);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return s;
    }
    // 以application/json ge's上传文件以及传参数,其中 tagIds类型为List<String>
    public String post3(String url, String localFile, Map<String,Object>param) throws FileNotFoundException {
        BufferedReader in = null;
        String s="";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httppost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(100000).setConnectionRequestTimeout(100000)
                .setSocketTimeout(100000).build();
        httppost.setConfig(requestConfig);
        System.out.println(Base64Util.getAuthorizationValue(getType(url)));
        httppost.addHeader("authorization", Base64Util.getAuthorizationValue(getType(url)));
        File file = new File(localFile);
        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
        multipartEntity.addBinaryBody("file", new FileInputStream(file), ContentType.DEFAULT_BINARY, file.getName());
        //设置传输参数
        for (Map.Entry<String, Object> stringStringEntry : param.entrySet()) {
            String key = stringStringEntry.getKey();
            StringBody value;
            if (key.equals("tagIds")){
                List<String>list= (List<String>) stringStringEntry.getValue();
                for (String ss:list){
                    value = new StringBody(ss, ContentType.create("multipart/form-data", Consts.UTF_8));
                    multipartEntity.addPart(key, value);
                }
            }else{
                value = new StringBody(stringStringEntry.getValue().toString(), ContentType.create("multipart/form-data", Consts.UTF_8));
                multipartEntity.addPart(key, value);
            }
        }
        HttpEntity reqEntity = multipartEntity.build();
        httppost.setEntity(reqEntity);
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httppost);
            // 从响应模型中获取响应实体
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            s = sb.toString();
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return s;
    }

    public String sendHttpPost(String url, String body) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        System.out.println(Base64Util.getAuthorizationValue(getType(url)));
        httpPost.addHeader("authorization", Base64Util.getAuthorizationValue(getType(url)));
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(body));

        CloseableHttpResponse response = httpClient.execute(httpPost);
        System.out.println(response.getStatusLine().getStatusCode() + "\n");
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseContent);

        response.close();
        httpClient.close();
        return responseContent;
    }


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!