Backend Development 4 min read

Using Java HttpClient to Simulate User Requests and Retrieve Cookies

This article explains how to simulate user HTTP requests in automated testing by sending GET/POST requests with Java, storing and extracting cookies from the application’s cookie store, and returning them as JSON, accompanied by a complete code example.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using Java HttpClient to Simulate User Requests and Retrieve Cookies

Automated testing often begins by simulating user requests, where the user's cookies are stored in the application's cookie store.

The following Java example demonstrates how to perform GET and POST requests using Apache HttpClient (and Hutool), capture cookies, and return them as a JSON object for further use in automated test scripts.

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class httpUtiles {
    //用于存储获取到的cookies
    static CookieStore cookieStore;
    private final static Logger logger;

    //post 获取 cookies
    public static String doPost2(String testUrl, JSONObject params) throws IOException {
        HttpPost post = new HttpPost(testUrl);
        StringEntity jsonEntity = new StringEntity(params.toString(), Consts.UTF_8);
        jsonEntity.setContentType("application/json;charset=utf-8");
        post.setEntity(jsonEntity);
        cookieStore = new BasicCookieStore();
        CloseableHttpClient closeableHttpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpResponse response = closeableHttpClient.execute(post);
        System.out.println("response1===========" + response);
        return "连接成功";
    }

    // get 获取 cookies
    public static JSONObject getCookies(String userTel) throws IOException {
        String result;
        //用来存储cookies信息的变量
        cookieStore = new BasicCookieStore();
        String debugurl = propertiesBundleValue.bundleValueTools("XXXURL.url") + propertiesBundleValue.bundleValueTools("Cookies.path") + userId;
        HttpGet get = new HttpGet(debugurl);
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(), "utf-8");
        // 获取cookies信息
        List
cookies = cookieStore.getCookies();
        String name = null;
        String value = null;
        for (Cookie cookie : cookies) {
            name = cookie.getName();
            value = cookie.getValue();
        }
        JSONObject cookiesJson = new JSONObject();
        cookiesJson.put(name, value);
        return cookiesJson;
    }
}
backendJavahttpAutomation Testingcookies
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.