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();
}
}