随笔 - 32,  文章 - 0,  评论 - 3,  阅读 - 39200

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<String, String> 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<Map.Entry<String, String>> entries = headerMap.entrySet();
                for (Map.Entry<String, String> 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);

 

复制代码
public String postData(String url, Map<String, Object> params) throws Exception {
        //创建post请求对象
        HttpPost httppost = new HttpPost(url);
        // 获取到httpclient客户端
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //创建参数集合
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            //添加请求头参数
//                    if(url.equals(GetOlapDataUrl)) {
//                          httppost.addHeader("Content-Type", "application/json");
//                          httppost.addHeader("accessToken",params.get("accessToken").toString());
//                      }
            // 设置请求的一些配置设置,主要设置请求超时,连接超时等参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(200000).setConnectionRequestTimeout(200000).setSocketTimeout(200000)
                    .build();
            httppost.setConfig(requestConfig);
            /**
             生产Cookie
             **/
            httppost.setHeader("Cookie","xxxxxx");
            //添加参数
            httppost.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.create("application/json", "utf-8")));
            // 请求结果
            String resultString = "";
            //启动执行请求,并获得返回值
            CloseableHttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 获取请求响应结果
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 将响应内容转换为指定编码的字符串
                    resultString = EntityUtils.toString(entity, "UTF-8");
                    System.out.printf("Response content:{}", resultString);
                    return resultString;
                }
            } else {
                System.out.println("请求失败!");
                return resultString;
            }
        } catch (Exception e) {
            throw e;
        } finally {
            httpclient.close();
        }
        return null;
    }
复制代码

 

posted on   大黑.的博客  阅读(220)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示