HttpClient---cookie(保持登录)

本文介绍了一个使用Java实现的HTTP客户端API方法,包括GET和POST请求的发送,响应结果的解析,Cookie的管理和设置等关键功能。该API适用于进行HTTP交互的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class APIMthod {
    // 创建CookieStore实例
    private static CookieStore cookieStore = null;
    private static HttpClientContext context = null;
    private static String response = "";

    public static String sendGetByHttpCient(String url){

        HttpResponse httpResponse = null;
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        try {
            HttpGet httpGet = new HttpGet(url);
            httpResponse = client.execute(httpGet);
            response = printResponse(httpResponse);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                // 关闭流并释放资源
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    public static String sendPostByHttpCient(String url, Map<String, String> parameterMap){
        HttpResponse httpResponse = null;
        UrlEncodedFormEntity postEntity = null;
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        try {
            HttpPost httpPost = new HttpPost(url);
            postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8");
            httpPost.setEntity(postEntity);

            httpResponse = client.execute(httpPost);
            response = printResponse(httpResponse);
            if (cookieStore == null || "".equals(cookieStore)) {
                String host = httpPost.getURI().getHost();
                setCookieStore(httpResponse, host);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                // 关闭流并释放资源
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    public static String printResponse(HttpResponse httpResponse) throws ParseException, IOException {
        String responseString = "";
        // 获取响应消息实体
        HttpEntity entity = httpResponse.getEntity();
        // 判断响应实体是否为空
        if (entity != null) {
            responseString = EntityUtils.toString(entity);
        }
        return responseString;
    }

    public static void setContext() {
        context = HttpClientContext.create();
        Registry<CookieSpecProvider> registry = RegistryBuilder
                .<CookieSpecProvider> create()
                .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
                .register(CookieSpecs.BROWSER_COMPATIBILITY,
                        new BrowserCompatSpecFactory()).build();
        context.setCookieSpecRegistry(registry);
        context.setCookieStore(cookieStore);
    }

    public static void setCookieStore(HttpResponse httpResponse,String host) {
        cookieStore = new BasicCookieStore();
        // JSESSIONID
        if (null == httpResponse.getFirstHeader("Set-Cookie")) {
            cookieStore = null;
        }else {
            String setCookie = httpResponse.getFirstHeader("Set-Cookie").getValue();
            String JSESSIONID = setCookie.substring("JSESSIONID=".length(),setCookie.indexOf(";"));
            // 新建一个Cookie
            BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",JSESSIONID);
            cookie.setVersion(0);
            cookie.setDomain(host);
            cookie.setPath("/");
            cookieStore.addCookie(cookie);
        }
    }

    public static List<Cookie> getCookies(){
        if (null == cookieStore) {
            return null;
        }
        return cookieStore.getCookies();
    }

    public static void deleteCookies(){
        if (cookieStore != null) {
            cookieStore.clear();
            cookieStore = null;
        }
    }

    public static List<NameValuePair> getParam(Map<String, String> parameterMap) {
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        Iterator it = parameterMap.entrySet().iterator();
        while (it.hasNext()) {
            Entry parmEntry = (Entry) it.next();
            param.add(new BasicNameValuePair((String) parmEntry.getKey(),(String) parmEntry.getValue()));
        }
        return param;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值