下面列出了怎么用org.apache.http.impl.client.BasicCookieStore的API类实例代码及写法,或者点击链接到github查看源代码。
private HttpClientContext convertHttpClientContext(Request request, Site site, Proxy proxy) {
HttpClientContext httpContext = new HttpClientContext();
if (proxy != null && proxy.getUsername() != null) {
AuthState authState = new AuthState();
authState.update(new BasicScheme(ChallengeState.PROXY), new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
httpContext.setAttribute(HttpClientContext.PROXY_AUTH_STATE, authState);
}
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
CookieStore cookieStore = new BasicCookieStore();
for (Map.Entry<String, String> cookieEntry : request.getCookies().entrySet()) {
BasicClientCookie cookie1 = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
cookie1.setDomain(UrlUtils.removePort(UrlUtils.getDomain(request.getUrl())));
cookieStore.addCookie(cookie1);
}
httpContext.setCookieStore(cookieStore);
}
return httpContext;
}
public RealmsAPI(AuthData authData) {
BasicCookieStore cookies = new BasicCookieStore();
BasicClientCookie sidCookie = new BasicClientCookie("sid", String.join(":", "token", authData.getAccessToken(), authData.getProfile()));
BasicClientCookie userCookie = new BasicClientCookie("user", authData.getUsername());
BasicClientCookie versionCookie = new BasicClientCookie("version", ProtocolConstants.getVersionString(FishingBot.getInstance().getServerProtocol()));
sidCookie.setDomain(".pc.realms.minecraft.net");
userCookie.setDomain(".pc.realms.minecraft.net");
versionCookie.setDomain(".pc.realms.minecraft.net");
sidCookie.setPath("/");
userCookie.setPath("/");
versionCookie.setPath("/");
cookies.addCookie(sidCookie);
cookies.addCookie(userCookie);
cookies.addCookie(versionCookie);
client = HttpClientBuilder.create()
.setDefaultCookieStore(cookies)
.build();
}
public CMODataAbapClient(String endpoint, String user, String password) throws URISyntaxException {
this.endpoint = new URI(endpoint);
this.requestBuilder = new TransportRequestBuilder(this.endpoint);
// the same instance needs to be used as long as we are in the same session. Hence multiple
// clients must share the same cookie store. Reason: we are logged on with the first request
// and get a cookie. That cookie - expressing the user has already been logged in - needs to be
// present in all subsequent requests.
CookieStore sessionCookieStore = new BasicCookieStore();
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider.setCredentials(
new AuthScope(this.endpoint.getHost(), this.endpoint.getPort()),
new UsernamePasswordCredentials(user, password));
this.clientFactory = new HttpClientFactory(sessionCookieStore, basicCredentialsProvider);
}
public static CookieStore getuCookie() {
CookieStore uCookie = new BasicCookieStore();
try {
String COOKIE_S_LINKDATA = LemallPlatform.getInstance().getCookieLinkdata();
if (!TextUtils.isEmpty(COOKIE_S_LINKDATA)) {
String[] cookies = COOKIE_S_LINKDATA.split("&");
for (String item : cookies) {
String[] keyValue = item.split(SearchCriteria.EQ);
if (keyValue.length == 2) {
if (OtherUtil.isContainsChinese(keyValue[1])) {
keyValue[1] = URLEncoder.encode(keyValue[1], "UTF-8");
}
BasicClientCookie cookie = new BasicClientCookie(keyValue[0], keyValue[1]);
cookie.setVersion(0);
cookie.setDomain(".lemall.com");
cookie.setPath("/");
uCookie.addCookie(cookie);
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return uCookie;
}
@Override
public void run() {
try {
if (file.length() > fileSizeLimit) {
throw new NUMaxFileSizeException(fileSizeLimit, file.getName(), this.getHost());
}
if (solidfilesAccount.loginsuccessful) {
httpContext = solidfilesAccount.getHttpContext();
}
else {
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}
uploadInitialising();
fileupload();
} catch(NUException ex){
ex.printError();
uploadInvalid();
} catch (Exception e) {
Logger.getLogger(Solidfiles.class.getName()).log(Level.SEVERE, null, e);
uploadFailed();
}
}
public HttpTransportClient(int retryAttemptsNetworkErrorCount, int retryAttemptsInvalidStatusCount) {
this.retryAttemptsNetworkErrorCount = retryAttemptsNetworkErrorCount;
this.retryAttemptsInvalidStatusCount = retryAttemptsInvalidStatusCount;
CookieStore cookieStore = new BasicCookieStore();
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SOCKET_TIMEOUT_MS)
.setConnectTimeout(CONNECTION_TIMEOUT_MS)
.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
.setCookieSpec(CookieSpecs.STANDARD)
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(MAX_SIMULTANEOUS_CONNECTIONS);
connectionManager.setDefaultMaxPerRoute(MAX_SIMULTANEOUS_CONNECTIONS);
httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.setDefaultCookieStore(cookieStore)
.setUserAgent(USER_AGENT)
.build();
}
public String PostInformation(String url, Map<String, String> map)
throws ClientProtocolException, IOException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> set = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator
.next();
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
cookieStore = new BasicCookieStore();
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(post);
int status = httpResponse.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
}
return null;
} else {
return null;
}
}
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException,
IOException {
BasicClientCookie cookie = new BasicClientCookie(cookieName, cookieValue);
cookie.setVersion(0);
cookie.setPath("/");
cookie.setDomain(jetty.getBaseUrl().getHost());
CookieStore cookieStore = new BasicCookieStore();
CookieSpec cookieSpec = new SolrPortAwareCookieSpecFactory().create(context);
// CookieSpec cookieSpec = registry.lookup(policy).create(context);
// Add the cookies to the request
List<Header> headers = cookieSpec.formatCookies(Collections.singletonList(cookie));
for (Header header : headers) {
request.addHeader(header);
}
context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from RapidU.net");
//responseString = NUHttpClientUtils.getData("https://rapidu.net", httpContext);
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from VodLocker.com");
//responseString = NUHttpClientUtils.getData("http://vodlocker.com", httpContext);
}
protected HttpClientContext createHttpClientContextForUser(final CloseableHttpClient httpClient, String userName, String password) throws IOException {
final HttpClientContext context = HttpClientContext.create();
CookieStore cookieStore = new BasicCookieStore();
context.setCookieStore(cookieStore);
HttpUriRequest request = handleLogin(getPageContent(oauth.getLoginFormUrl(), httpClient, context), userName, password);
Assert.assertThat(parseAndCloseResponse(httpClient.execute(request, context)), containsString("<title>AUTH_RESPONSE</title>"));
return context;
}
@Test
public void testBuildHttpClientAllPossible()
{
String baseUrl = "http://somewh.ere/";
config.setBaseUrl(baseUrl);
config.setHeadersMap(HEADERS);
config.setCredentials(CREDS);
config.setAuthScope(AUTH_SCOPE);
config.setSslCertificateCheckEnabled(false);
config.setSkipResponseEntity(true);
CookieStore cookieStore = new BasicCookieStore();
config.setCookieStore(cookieStore);
config.setSslHostnameVerificationEnabled(false);
DnsResolver resolver = mock(DnsResolver.class);
config.setDnsResolver(resolver);
SSLContext mockedSSLContext = mock(SSLContext.class);
when(mockedSSLContextManager.getSslContext(SSLConnectionSocketFactory.SSL, true))
.thenReturn(Optional.of(mockedSSLContext));
prepareClientBuilderUtilsMock();
testBuildHttpClientUsingConfig();
verify(mockedHttpClientBuilder).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
verify(mockedHttpClient).setHttpHost(HttpHost.create(baseUrl));
verify(mockedHttpClient).setSkipResponseEntity(config.isSkipResponseEntity());
verify(mockedHttpClientBuilder).setSSLContext(mockedSSLContext);
verify(mockedHttpClientBuilder).setDefaultCredentialsProvider(credentialsProvider);
verify(mockedHttpClientBuilder).setDefaultCookieStore(cookieStore);
verify(mockedHttpClientBuilder).setDnsResolver(resolver);
verifyDefaultHeaderSetting(HEADERS.entrySet().iterator().next());
PowerMockito.verifyStatic(ClientBuilderUtils.class);
ClientBuilderUtils.createCredentialsProvider(AUTH_SCOPE, CREDS);
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from LomaFile.com");
//responseString = NUHttpClientUtils.getData("http://lomafile.com", httpContext);
}
private HttpClient(){
/**
* 请求配置
*/
RequestConfig globalConfig = RequestConfig.
custom().
setCookieSpec(CookieSpecs.DEFAULT).
setSocketTimeout(10000).
setConnectTimeout(20000).
setConnectionRequestTimeout(20000).
build();
/**
* cookie容器
*/
CookieStore cookieStore = new BasicCookieStore();
/**
* 核心请求对象
*/
httpclient = HttpClients.
custom().
setDefaultRequestConfig(globalConfig).
setDefaultCookieStore(cookieStore).
setRetryHandler(new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int retryTimes, HttpContext httpContext) {
if(retryTimes > 10){ //最多重试10次
return false;
}
if(Arrays.asList(InterruptedIOException.class, UnknownHostException.class, ConnectException.class, SSLException.class).contains(exception.getClass())){ //此类异常不进行重试
return false;
}
return true; //重点是这,非幂等的post请求也进行重试
}
}).
build();
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from GBoxes.com");
//responseString = NUHttpClientUtils.getData("http://www.gboxes.com", httpContext);
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
NULogger.getLogger().info("Getting startup cookies & link from CatShare.net");
responseString = NUHttpClientUtils.getData("http://catshare.net/login", httpContext);
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from IndiShare.com");
//responseString = NUHttpClientUtils.getData("http://www.indishare.com/", httpContext);
}
@Test
public void test03() throws IOException, SchedulisSchedulerException {
Cookie cookie = test01();
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("ajax","fetchProjectPage"));
params.add(new BasicNameValuePair("start","0"));
params.add(new BasicNameValuePair("length","10"));
params.add(new BasicNameValuePair("projectsType","personal"));
params.add(new BasicNameValuePair("pageNum","1"));
params.add(new BasicNameValuePair("order","orderProjectName"));
CookieStore cookieStore = new BasicCookieStore();
cookieStore.addCookie(cookie);
HttpClientContext context = HttpClientContext.create();
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
try {
String finalUrl = "http://127.0.0.1:8088/index" + "?" + EntityUtils.toString(new UrlEncodedFormEntity(params));
HttpGet httpGet = new HttpGet(finalUrl);
httpGet.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
response = httpClient.execute(httpGet, context);
/*Header[] allHeaders = context.getRequest().getAllHeaders();
Optional<Header> header = Arrays.stream(allHeaders).filter(f -> "Cookie".equals(f.getAppJointName())).findFirst();
header.ifPresent(AzkabanUtils.handlingConsumerWrapper(this::parseCookie));*/
} catch (Exception e) {
throw new SchedulisSchedulerException(90004, e.getMessage());
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(httpClient);
}
}
private CloseableHttpClient buildHttpClient() {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials("tivo", mak));
CookieStore cookieStore = new BasicCookieStore();
ConnectionConfig connConfig = ConnectionConfig.custom().setBufferSize(BUFFER_SIZE).build();
return HttpClients.custom()
.useSystemProperties()
.setDefaultConnectionConfig(connConfig)
.setDefaultCredentialsProvider(credsProvider)
.setDefaultCookieStore(cookieStore)
.setUserAgent(Archivo.USER_AGENT)
.build();
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from KingFiles.net");
//responseString = NUHttpClientUtils.getData("http://www.kingfiles.net", httpContext);
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from TusFiles.net");
//responseString = NUHttpClientUtils.getData("http://www.tusfiles.net", httpContext);
}
/**
* delete=boolean
* project=projectName
*
* @param project
* @param session
*/
@Override
public void deleteProject(Project project, Session session) throws AppJointErrorException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("delete", "true"));
params.add(new BasicNameValuePair("project", project.getName()));
CookieStore cookieStore = new BasicCookieStore();
cookieStore.addCookie(session.getCookies()[0]);
HttpClientContext context = HttpClientContext.create();
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
try {
String finalUrl = projectUrl + "?" + EntityUtils.toString(new UrlEncodedFormEntity(params));
HttpGet httpGet = new HttpGet(finalUrl);
httpGet.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
response = httpClient.execute(httpGet, context);
Header[] allHeaders = context.getRequest().getAllHeaders();
Optional<Header> header = Arrays.stream(allHeaders).filter(f -> "Cookie".equals(f.getName())).findFirst();
header.ifPresent(DSSExceptionUtils.handling(this::parseCookie));
} catch (Exception e) {
logger.error("delete scheduler project failed,reason:",e);
throw new AppJointErrorException(90010, e.getMessage(), e);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(httpClient);
}
}
private void uploadProject(String tmpSavePath, Project project, Cookie cookie) throws AppJointErrorException {
String projectName = project.getName();
HttpPost httpPost = new HttpPost(projectUrl + "?project=" + projectName);
httpPost.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
CloseableHttpResponse response = null;
File file = new File(tmpSavePath);
CookieStore cookieStore = new BasicCookieStore();
cookieStore.addCookie(cookie);
CloseableHttpClient httpClient = null;
InputStream inputStream = null;
try {
httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.addBinaryBody("file",file);
entityBuilder.addTextBody("ajax", "upload");
entityBuilder.addTextBody("project", projectName);
httpPost.setEntity(entityBuilder.build());
response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
inputStream = httpEntity.getContent();
String entStr = null;
entStr = IOUtils.toString(inputStream, "utf-8");
if(response.getStatusLine().getStatusCode() != 200){
logger.error("调用azkaban上传接口的返回不为200, status code 是 {}", response.getStatusLine().getStatusCode());
throw new AppJointErrorException(90013, "release project failed, " + entStr);
}
logger.info("upload project:{} success!",projectName);
}catch (Exception e){
logger.error("upload failed,reason:",e);
throw new AppJointErrorException(90014,e.getMessage(), e);
}
finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(httpClient);
}
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from DropVideo.com");
//responseString = NUHttpClientUtils.getData("", httpContext);
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from IguanaShare.com");
//responseString = NUHttpClientUtils.getData("", httpContext);
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from Vip-File.com");
//responseString = NUHttpClientUtils.getData("http://vip-file.com", httpContext);
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from SendFile.su");
//responseString = NUHttpClientUtils.getData("SendFile.su", httpContext);
}
private BasicCookieStore getWebDriverCookies(Set<Cookie> seleniumCookieSet) {
BasicCookieStore copyOfWebDriverCookieStore = new BasicCookieStore();
for (Cookie seleniumCookie : seleniumCookieSet) {
BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
duplicateCookie.setDomain(seleniumCookie.getDomain());
duplicateCookie.setSecure(seleniumCookie.isSecure());
duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());
duplicateCookie.setPath(seleniumCookie.getPath());
copyOfWebDriverCookieStore.addCookie(duplicateCookie);
}
return copyOfWebDriverCookieStore;
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//NULogger.getLogger().info("Getting startup cookies & link from NowDownload.to");
//responseString = NUHttpClientUtils.getData("http://www.nowdownload.to", httpContext);
}
private void initialize() throws Exception {
httpContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
httpPost = new NUHttpPost("http://www.promptfile.com/modal.php");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("modal", "login"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPost.setEntity(entity);
httpResponse = httpclient.execute(httpPost, httpContext);
responseString = EntityUtils.toString(httpResponse.getEntity());
p = Pattern.compile("sid=[a-z0-9]*(?=\")");
m = p.matcher(responseString);
while (m.find()){
captcha_sid = m.group();
}
captcha_url = "http://www.promptfile.com/securimage_show.php?" + captcha_sid;
Captcha captcha = captchaServiceProvider().newCaptcha();
captcha.setFormTitle(Translation.T().captchacontrol()+" (PromptFile.com)");
captcha.setImageURL(captcha_url);
captcha.setHttpContext(httpContext);
captchaString = captcha.getCaptchaString();
}