java模拟cookie_java 模拟cookie 调用httpget请求

该篇博客展示了如何使用Apache HttpClient库在Java中模拟Cookie并执行HTTP GET请求。通过创建`BasicCookieStore`,设置`BasicClientCookie`,并将它们应用于`CloseableHttpClient`,实现了携带Cookie的HTTP请求。博客内容包括读取文件、循环处理请求以及处理响应的步骤。
摘要由CSDN通过智能技术生成

import org.apache.commons.io.FileUtils;

import org.apache.http.HttpEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

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.impl.cookie.BasicClientCookie;

import org.apache.http.util.EntityUtils;

import org.junit.Test;

import java.io.File;

import java.io.IOException;

import java.util.List;

import java.util.concurrent.TimeUnit;

/**

* 模拟cookie 调用 http请求

*/

public class CookieTest {

@Test

public void testpublish() throws IOException {

String urlTemplate = "http://ceshi/%s";

//把文件内容转换为字符串集合,每行为一个字符串对象

List tempIds = FileUtils.readLines(new File("e:\\tmp\\ceshi.txt"));

//实际调用接口用到的cookie 里的数据,可以循环多个

BasicCookieStore cookieStore = new BasicCookieStore();

BasicClientCookie cookie = new BasicClientCookie("user", "ceshi");

cookie.setDomain(".ceshi.com");

cookie.setPath("/");

cookieStore.addCookie(cookie);

BasicClientCookie cookie1 = new BasicClientCookie("thor", "ceshi");

cookie1.setDomain(".ceshi.com");

cookie1.setPath("/");

cookieStore.addCookie(cookie1);

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

for (String tempId : tempIds) {

String url = String.format(urlTemplate, tempId.trim());

System.out.println("url = " + url);

HttpGet httpGet = new HttpGet(url);

CloseableHttpResponse httpResponse = client.execute(httpGet);

// 响应状态

System.out.println("status:" + httpResponse.getStatusLine());

HttpEntity entity = httpResponse.getEntity();

String s = EntityUtils.toString(entity);

System.out.println("entity s = " + s);

httpResponse.close();

// 休眠1s

try {

TimeUnit.MILLISECONDS.sleep(500);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

client.close();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值