Java Example for Retrieving Cookies in API Automation Using Apache HttpClient
The article demonstrates how to configure API endpoints and use Java's Apache HttpClient to retrieve authentication cookies and perform subsequent requests, providing a full code example for beginners in interface automation testing.
The article introduces a basic approach for API automation that requires login information such as cookies, tokens, or session data, and provides a complete Java example using Apache HttpClient to obtain cookies and make subsequent authenticated requests.
The example shows how to store domain and path settings in an application.properties file, read them with ResourceBundle, configure a global request with standard cookie handling, create a local CookieStore and HttpClientContext, and execute a GET request to capture cookies (including XSRF tokens). After collecting the cookies, a second test method demonstrates using the same cookies to call another endpoint and print the response.
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DecompressingHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ResourceBundle;
/**
* @author : huaan9527
* create at: 2021/2/23 下午7:07
* @description: 获取debug-demo
*/
public class firstHttpCookiesDemo {
private String debugurl;
private String buyerCenterurl;
private ResourceBundle bundle;
//获取配置文件中域名
@BeforeTest
public void befroeTest() {
bundle = ResourceBundle.getBundle("application");
debugurl = bundle.getString("debug.uri");
}
//获取cookies
@Test
public void getCookies() throws IOException {
//从配置文件中,拼接debug url
String uri = bundle.getString("debug.path");
String url = this.debugurl + uri;
// 全局请求设置
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
// 创建cookie store的本地实例
CookieStore cookieStore = new BasicCookieStore();
// 创建HttpClient上下文
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
// 创建一个HttpClient
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
.setDefaultCookieStore(cookieStore).build();
CloseableHttpResponse res = null;
// 创建一个get请求用来获取必要的Cookie,如_xsrf信息
HttpGet get = new HttpGet(url);
res = httpClient.execute(get, context);
// 获取常用Cookie,包括_xsrf信息
StringBuffer cookie = new StringBuffer();
for (Cookie c : cookieStore.getCookies()) {
//拼接所有cookie变成一个字符串;
cookie.append(c.getName() + "=" + c.getValue() + ";");
System.out.println(c.getValue());
}
}
@Test(dependsOnMethods = {"getCookies"})
//todo 获取接口返回值
public void requestMybuyerCenter() throws IOException {
//从配置文件中,拼接debug url
String uri = bundle.getString("buyerCenter.path");
String testbuyerCenterurl = this.debugurl + uri;
String result;
//测试逻辑代码书写
System.out.println("testbuyerCenterurl = " + testbuyerCenterurl);
HttpGet get = new HttpGet(testbuyerCenterurl);
HttpClient client = new DecompressingHttpClient();
HttpResponse response = client.execute(get);
result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(result);
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
