http发送请求的几种方式笔记


CloseableHttpResponse方式

get请求

 public String logoutByToken (String token)throws IOException {
        String code =null;

        if(token == null){
            return "500";

        }else {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpPost = new HttpGet("url);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            String responseResult = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(responseResult);
            code = jsonObject.getString("code");
            System.out.println("logoutByToken:" + responseResult);
            response.close();
            httpClient.close();
        } catch (Exception e) {
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
        }
        return code;
    }

HttpURLConnection方式

    public String sendHTTPS(String method, String url, Map headerMap, String requestBody) {
        OutputStream out = null;
        BufferedReader in = null;
        try {
            URL serverUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
            conn.setRequestMethod(method);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            if (headerMap != null && headerMap.size() > 0) {
                Set> entries = headerMap.entrySet();
                for (Map.Entry e : entries) {
                    conn.setRequestProperty(e.getKey(), e.getValue());
                }
            }

            conn.setInstanceFollowRedirects(false);
            conn.connect();

            if (method.equals("POST") && requestBody != null) {
                out = conn.getOutputStream();
                out.write(requestBody.getBytes("utf-8"));
                out.flush();
            }

            StringBuffer buffer = new StringBuffer();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String str = null;
            while ((str = in.readLine()) != null) {
                buffer.append(str);
            }
            return buffer.toString();

        } catch (IOException e) {
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (null != in) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }



}
HttpUtil方式
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * 调用接口
 *
 * @author tangyi
 * @date 2019/9/11 16:43
 */
public class HttpUtil {
    /**
     * post方式调用接口
     *
     * @param url        远程接口url
     * @param jsonString JSON参数
     * @return String
     * @throws Exception 异常
     */
    public static String post(String url, String jsonString) throws Exception {
        // 打造请求体,设置编码
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8");
        httpPost.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
        // 设置JSON参数
        StringEntity entity = new StringEntity(jsonString, Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        // 打造客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 发送请求,获得结果
        HttpResponse response = httpClient.execute(httpPost);
        // 获取返回结果
        HttpEntity entitys = response.getEntity();
        BufferedReader in = new BufferedReader(new InputStreamReader(entitys.getContent(), "UTF-8"));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        in.close();
        return buffer.toString();
    }

    /**
     * post方式调用接口
     *
     * @param url        远程接口url
     * @param jsonString JSON参数
     * @return String
     * @throws Exception 异常
     */
    public static String postTextPlain(String url, String jsonString) throws Exception {
        // 打造请求体,设置编码
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "text/plain; charset=utf-8");
        httpPost.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
        // 设置JSON参数
        StringEntity entity = new StringEntity(jsonString, Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        // 打造客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 发送请求,获得结果
        HttpResponse response = httpClient.execute(httpPost);
        // 获取返回结果
        HttpEntity entitys = response.getEntity();
        BufferedReader in = new BufferedReader(new InputStreamReader(entitys.getContent(), "UTF-8"));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        in.close();
        return buffer.toString();
    }
}
调用httpUtil

String requestJson = JSON.toJSONString(vo);
String result = HttpUtil.httpPost(url, requestJson);