Java Code Examples for org.apache.http.client.protocol.HttpClientContext#setCookieStore()

The following examples show how to use org.apache.http.client.protocol.HttpClientContext#setCookieStore() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpUriRequestConverter.java    From webmagic with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 6 votes vote down vote up
/**
 * https://upay.10010.com/npfweb/NpfWeb/buyCard/checkPhoneVerifyCode?callback=checkSuccess&commonBean.phoneNo=13249073372&phoneVerifyCode=932453&timeStamp=0.3671002044464746
 * @throws ParseException
 * @throws Exception
 * sendSuccess('true') 返回格式
 */
@Test
public void checkChargeSms() throws ParseException, Exception {
	String mobile = "13249073372";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("commonBean.phoneNo", Lists.newArrayList(mobile));
	params.put("phoneVerifyCode", Lists.newArrayList("904114"));
	params.put("timeStamp", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));

	String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/checkPhoneVerifyCode").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://upay.10010.com/npfweb/npfbuycardweb/buycard_recharge_fill.htm");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example 3
Source File: Session.java    From timer with Apache License 2.0 6 votes vote down vote up
public Session process() throws IOException {

        HttpRequest request = this.getRequest();
        Objects.requireNonNull(this.request);
        HttpClient httpClient = this.getHttpClient();
        HttpClientContext context = this.getContext();
        if (request instanceof HttpGet) {
            this.getContext().setCookieStore(cookies);
            HttpGet get = (HttpGet) request;
            this.httpResponse = httpClient.execute(get, context);
            this.httpCode = httpResponse.getStatusLine().getStatusCode();
            this.repUtils = new ResponseUtils(this.httpResponse);
        } else if (this.request instanceof HttpPost) {
            context.setCookieStore(cookies);
            HttpPost post = (HttpPost) request;
            post.setEntity(this.getProviderService().builder());
            this.httpResponse = this.httpClient.execute(post, this.context);
            this.httpCode = httpResponse.getStatusLine().getStatusCode();
            this.repUtils = new ResponseUtils(this.httpResponse);
        }
        return this;
    }
 
Example 4
Source File: AsyncClientCustomContext.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public final static void main(String[] args) throws Exception {
	CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
	try {
		// Create a local instance of cookie store
		CookieStore cookieStore = new BasicCookieStore();

		// Create local HTTP context
		HttpClientContext localContext = HttpClientContext.create();
		// Bind custom cookie store to the local context
		localContext.setCookieStore(cookieStore);

           HttpGet httpget = new HttpGet("http://localhost/");
		System.out.println("Executing request " + httpget.getRequestLine());

		httpclient.start();

		// Pass local context as a parameter
		Future<HttpResponse> future = httpclient.execute(httpget, localContext, null);

		// Please note that it may be unsafe to access HttpContext instance
		// while the request is still being executed

		HttpResponse response = future.get();
		System.out.println("Response: " + response.getStatusLine());
		List<Cookie> cookies = cookieStore.getCookies();
		for (int i = 0; i < cookies.size(); i++) {
			System.out.println("Local cookie: " + cookies.get(i));
		}
		System.out.println("Shutting down");
	} finally {
		httpclient.close();
	}
}
 
Example 5
Source File: VaryMasterTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
/**
 * Send a request with a Cookie "test-cookie" to vary.jsp (which will get content from provider) and ensure the
 * result is valid.
 * 
 * @param cookieValue
 * @param forceRefresh
 * @return Page timestamp. Can be used to detect cache hits.
 * @throws Exception
 */
private String doCookieRequest(String cookieValue, boolean forceRefresh) throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = new HttpClientContext();
    context.setCookieStore(cookieStore);
    CloseableHttpClient client = HttpClients.createDefault();
    RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
    HttpGet request = new HttpGet("http://localhost:8080/esigate-app-master/vary.jsp");
    request.setConfig(config);

    if (cookieValue != null) {
        BasicClientCookie cookie = new BasicClientCookie("test-cookie", cookieValue);
        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookieStore.addCookie(cookie);
    }
    if (forceRefresh) {
        request.addHeader("Cache-Control", "no-cache");
    }
    HttpResponse response = client.execute(request, context);
    // Ensure content is valid.
    String text = IOUtils.toString(response.getEntity().getContent());
    assertNotNull(text);
    LOG.debug("----- Request with cookie " + cookieValue + " and forceRefresh=" + forceRefresh + " -----> \n"
            + text);
    if (cookieValue != null) {
        assertTrue("no value '" + cookieValue + "' found", text.contains(cookieValue));
    } else {
        assertTrue("no cookie found", text.contains("no cookie"));
    }

    client.close();

    return text.substring(text.indexOf("stime") + 5, text.indexOf("etime"));
}
 
Example 6
Source File: OAuthRedirectUriTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithCustomScheme() throws IOException {
    oauth.clientId("custom-scheme");

    oauth.redirectUri("android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login");
    oauth.openLoginForm();

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    String loginUrl = driver.getCurrentUrl();

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

    try {
        String loginPage = SimpleHttp.doGet(loginUrl, client).asString();

        String formAction = loginPage.split("action=\"")[1].split("\"")[0].replaceAll("&amp;", "&");
        SimpleHttp.Response response = SimpleHttp.doPost(formAction, client).param("username", "test-user@localhost").param("password", "password").asResponse();

        response.getStatus();
        assertThat(response.getFirstHeader("Location"), Matchers.startsWith("android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login"));
    } finally {
        client.close();
    }
}
 
Example 7
Source File: BasicTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void loginError() throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(new BasicCookieStore());

    // 1. first GET to fetch execution
    HttpGet get = new HttpGet(getLoginURL());
    get.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
    CloseableHttpResponse response = httpclient.execute(get, context);
    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    String responseBody = EntityUtils.toString(response.getEntity());
    int begin = responseBody.indexOf("name=\"execution\" value=\"");
    assertNotEquals(-1, begin);
    int end = responseBody.indexOf("\"/><input type=\"hidden\" name=\"_eventId\"");
    assertNotEquals(-1, end);

    String execution = responseBody.substring(begin + 24, end);
    assertNotNull(execution);

    // 2. then POST to authenticate
    List<NameValuePair> form = new ArrayList<>();
    form.add(new BasicNameValuePair("_eventId", "submit"));
    form.add(new BasicNameValuePair("execution", execution));
    form.add(new BasicNameValuePair("username", "mrossi"));
    form.add(new BasicNameValuePair("password", "WRONG"));
    form.add(new BasicNameValuePair("geolocation", ""));

    HttpPost post = new HttpPost(getLoginURL());
    post.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
    post.setEntity(new UrlEncodedFormEntity(form, Consts.UTF_8));
    response = httpclient.execute(post, context);

    // 3. check authentication results
    assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
}
 
Example 8
Source File: HttpUtil.java    From ZhihuSpider with MIT License 5 votes vote down vote up
public static boolean deserializeCookie(String path, HttpClientContext httpClientContext) {
    try {
        CookieStore cookieStore = (CookieStore) deserializeMyContext(path);
        httpClientContext.setCookieStore(cookieStore);
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example 9
Source File: AemAuthCookieFactoryImpl.java    From bobcat with Apache License 2.0 5 votes vote down vote up
/**
 * This method provides browser cookie for authenticating user to AEM instance
 *
 * @param url      URL to AEM instance, like http://localhost:4502
 * @param login    Username to use
 * @param password Password to use
 * @return Cookie for selenium WebDriver.
 */
@Override
public Cookie getCookie(String url, String login, String password) {
  if (!cookieJar.containsKey(url)) {
    HttpPost loginPost = new HttpPost(url
        + "/libs/granite/core/content/login.html/j_security_check");

    List<NameValuePair> nameValuePairs = new ArrayList<>();
    nameValuePairs.add(new BasicNameValuePair("_charset_", "utf-8"));
    nameValuePairs.add(new BasicNameValuePair("j_username", login));
    nameValuePairs.add(new BasicNameValuePair("j_password", password));
    nameValuePairs.add(new BasicNameValuePair("j_validate", "true"));

    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    try {
      loginPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      CloseableHttpResponse loginResponse = httpClient.execute(loginPost, context);
      loginResponse.close();
    } catch (IOException e) {
      LOG.error("Can't get AEM authentication cookie", e);
    } finally {
      loginPost.reset();
    }
    Cookie cookie = findAuthenticationCookie(cookieStore.getCookies());
    cookieJar.put(url, cookie);
  }
  return cookieJar.get(url);
}
 
Example 10
Source File: HttpClientUtil.java    From feiqu-opensource with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpResponse getResponse(HttpRequestBase request) throws IOException {
        if (request.getConfig() == null){
            request.setConfig(requestConfig);
        }
        request.setHeader("User-Agent", CommonConstant.userAgentArray[new Random().nextInt(CommonConstant.userAgentArray.length)]);
        HttpClientContext httpClientContext = HttpClientContext.create();
        httpClientContext.setCookieStore(cookieStore);
        CloseableHttpResponse response = httpClient.execute(request, httpClientContext);
//		int statusCode = response.getStatusLine().getStatusCode();
//		if(statusCode != 200){
//			throw new IOException("status code is:" + statusCode);
//		}
        return response;
    }
 
Example 11
Source File: ConcurrentLoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * https://upay.10010.com/npfweb/NpfWeb/buyCard/buyCardCheck?
 * cardBean.cardValueCode=04&offerPriceStrHidden=100.00
 * &offerRateStrHidden=1&cardBean.cardValue=100&cardBean.minCardNum=1
 * &cardBean.maxCardNum=3&MaxThreshold01=15&MinThreshold01=1&MaxThreshold02=10
 * &MinThreshold02=1&MaxThreshold03=6&MinThreshold03=1&MaxThreshold04=3
 * &MinThreshold04=1&commonBean.channelType=101
 * &secstate.state=3mCBuETgA%2FYTbuZO79gHFA%3D%3D%5E%40%5E0.0.1
 * &cardBean.buyCardAmount=1&cardBean.buyCardEmail=734839030%40qq.com
 * &cardBean.buyCardPhoneNo=13249073372&phoneVerifyCode=419906
 * &invoiceBean.need_invoice=0&invoiceBean.invoice_type=
 * &invoiceBean.is_mailing=0&saveflag=false&commonBean.provinceCode=&commonBean.cityCode=&invoiceBean.invoice_list=
 * {"secstate":""}
 */
@Test
public void order() throws ParseException, Exception {
	String mobile = "13249073372";
	String email= "[email protected]";
	String phoneVerifyCode="874501";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/buyCardCheck").query("cardBean.cardValueCode=04&offerPriceStrHidden=100.00&offerRateStrHidden=1&cardBean.cardValue=100&cardBean.minCardNum=1&cardBean.maxCardNum=3&MaxThreshold01=15&MinThreshold01=1&MaxThreshold02=10&MinThreshold02=1&MaxThreshold03=6&MinThreshold03=1&MaxThreshold04=3&MinThreshold04=1&commonBean.channelType=101&secstate.state=3mCBuETgA%2FYTbuZO79gHFA%3D%3D%5E%40%5E0.0.1&cardBean.buyCardAmount=1&cardBean.buyCardEmail=" + email+ "&cardBean.buyCardPhoneNo=" + mobile+ "&phoneVerifyCode=" + phoneVerifyCode +"&invoiceBean.need_invoice=0&invoiceBean.invoice_type=&invoiceBean.is_mailing=0&saveflag=false&commonBean.provinceCode=&commonBean.cityCode=&invoiceBean.invoice_list=").build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://upay.10010.com/npfweb/npfbuycardweb/buycard_recharge_fill.htm");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example 13
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * https://upay.10010.com/npfweb/NpfWeb/buyCard/sendPhoneVerifyCode?callback=sendSuccess&commonBean.phoneNo=13249073372&timeStamp=0.474434596328998
 * @throws ParseException
 * @throws Exception
 * sendSuccess('true') 返回格式
 */
@Test
public void chargeSms() throws ParseException, Exception {
	String mobile = "13249073372";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("commonBean.phoneNo", Lists.newArrayList(mobile));
	params.put("timeStamp", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));

	String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/sendPhoneVerifyCode").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://uac.10010.com/portal/custLogin");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example 14
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * https://uac.10010.com/portal/Service/SendMSG?callback=jQuery17205929719702722311_1528559748925&req_time=1528560335346&mobile=13249073372&_=1528560335347
 * @throws Exception 
 * @throws ParseException 
 */
@Test
public void sendSms() throws ParseException, Exception {
	CookieStore cookie = new BasicCookieStore() ;
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookie);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("req_time", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("_=", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("mobile", Lists.newArrayList("13249073372"));
	String url = UriComponentsBuilder.fromHttpUrl("https://uac.10010.com/portal/Service/SendMSG").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://uac.10010.com/portal/custLogin");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
	System.out.println("cookie:" + JSON.toJSONString(cookie));
	
}
 
Example 15
Source File: HC4DavExchangeSession.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a separate Http context to protect session cookies.
 *
 * @return HttpClientContext instance with cookies
 */
private HttpClientContext cloneContext() {
    // Create a local context to avoid cookie reset on error
    BasicCookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookies(httpClientAdapter.getCookies().toArray(new org.apache.http.cookie.Cookie[0]));
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);
    return context;
}
 
Example 16
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 4 votes vote down vote up
@Test
public void payPage() throws ParseException, Exception {
	String mobile = "13249073372";
	String email= "[email protected]";
	String phoneVerifyCode="874501";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/buyCardSubmit").build().toUriString();
	HttpPost request = new HttpPost(url);
	Map<String, String> params = new HashMap<String,String>();
	params.put("cardBean.cardValueCode", "04");
	params.put("offerPriceStrHidden", "100.00");
	params.put("offerRateStrHidden", "1");
	params.put("cardBean.cardValue", "100");
	params.put("cardBean.minCardNum", "1");
	params.put("cardBean.maxCardNum", "3");
	params.put("MaxThreshold01", "15");
	params.put("MinThreshold01", "1");
	params.put("MaxThreshold02", "10");
	params.put("MinThreshold02", "1");
	params.put("MaxThreshold03", "6");
	params.put("MinThreshold03", "1");
	params.put("MaxThreshold04", "3");
	params.put("MinThreshold04", "1");
	params.put("commonBean.channelType", "101");
	//params.put("secstate.state", IOUtils.toString(new FileReader("/Users/hdf/Desktop/1.txt")));
	params.put("secstate.state", "FYlSiTsg5fqfr+wYGrqIRsetX8HDhLNTieb9/vhIHd1T+Hn5TFUBZdV9xR8nsIPRJXIsCwNfl2X+\\nw0sbN+O733sOywtoDmSU3uaYdnBYqPe8IxAtxwFBfYu2KOg4tCVKpSHRz9YutD8oAE0p24CNzliO\\nGRr/Kmt8YTVIYBqI51b3JBw8HC/efyVNcK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+ZrrTL\\n9JfwSm9YD82ecsrgIuRBiuUDibk7thXTNISBcSxtLhuSdsfonEKVJNnKKNb5G9+b8+ZGEl/Zbbkm\\n6QstnWr9nQL4kb0VhZmZTJfzfx7x2DiV+/BqLDSReHo6^@^0.0.1");
	params.put("cardBean.buyCardAmount", "1");
	params.put("cardBean.buyCardEmail", email);
	params.put("cardBean.buyCardPhoneNo", mobile);
	params.put("phoneVerifyCode",phoneVerifyCode);
	params.put("invoiceBean.need_invoice", "	0");
	params.put("invoiceBean.invoice_type	", "");
	params.put("invoiceBean.is_mailing", "0");
	params.put("saveflag	", "false");
	params.put("commonBean.provinceCode", "");
	params.put("commonBean.cityCode", "");
	params.put("invoiceBean.invoice_list	", "");
	request.setEntity(getUrlEncodedFormEntity(params));
	request.setHeader("Referer", "https://upay.10010.com/npfweb/npfbuycardweb/buycard_recharge_fill.htm");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else if (response.getStatusLine().getStatusCode() == 302) {
		Header header = response.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD 中的
		String newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请,以便得到跳转后的信息是啥。
		System.out.println("redirect url:" + newuri);
		HttpGet redirectRequest = new HttpGet(newuri);
		CloseableHttpResponse response2 = client.execute(redirectRequest, httpClientContext);
		System.out.println("response2:" + JSON.toJSONString(response2));
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example 17
Source File: ConcurrentLoginTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void run(int threadIndex, Keycloak keycloak, RealmResource realm) throws Throwable {
    int i = sameClient ? 0 : clientIndex.getAndIncrement();
    OAuthClient oauth1 = oauthClient.get();
    oauth1.clientId("client" + i);
    log.infof("%d [%s]: Accessing login page for %s", threadIndex, Thread.currentThread().getName(), oauth1.getClientId());

    final HttpClientContext templateContext = clientContexts.get(i % clientContexts.size());
    final HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(templateContext.getCookieStore());
    String pageContent = getPageContent(oauth1.getLoginFormUrl(), httpClient, context);
    Assert.assertThat(pageContent, Matchers.containsString("<title>AUTH_RESPONSE</title>"));
    Assert.assertThat(context.getRedirectLocations(), Matchers.notNullValue());
    Assert.assertThat(context.getRedirectLocations(), Matchers.not(Matchers.empty()));
    String currentUrl = context.getRedirectLocations().get(0).toString();

    Map<String, String> query = getQueryFromUrl(currentUrl);
    String code = query.get(OAuth2Constants.CODE);
    String state = query.get(OAuth2Constants.STATE);

    Assert.assertEquals("Invalid state.", state, oauth1.getState());

    AtomicReference<OAuthClient.AccessTokenResponse> accessResRef = new AtomicReference<>();
    totalInvocations.incrementAndGet();

    // obtain access + refresh token via code-to-token flow
    OAuthClient.AccessTokenResponse accessRes = oauth1.doAccessTokenRequest(code, "password");
    Assert.assertEquals("AccessTokenResponse: client: " + oauth1.getClientId() + ", error: '" + accessRes.getError() + "' desc: '" + accessRes.getErrorDescription() + "'",
      200, accessRes.getStatusCode());
    accessResRef.set(accessRes);

    // Refresh access + refresh token using refresh token
    AtomicReference<OAuthClient.AccessTokenResponse> refreshResRef = new AtomicReference<>();

    int invocationIndex = Retry.execute(() -> {
        OAuthClient.AccessTokenResponse refreshRes = oauth1.doRefreshTokenRequest(accessResRef.get().getRefreshToken(), "password");
        Assert.assertEquals("AccessTokenResponse: client: " + oauth1.getClientId() + ", error: '" + refreshRes.getError() + "' desc: '" + refreshRes.getErrorDescription() + "'",
          200, refreshRes.getStatusCode());

        refreshResRef.set(refreshRes);
    }, retryCount, retryDelayMs);

    retryHistogram[invocationIndex].incrementAndGet();

    AccessToken token = JsonSerialization.readValue(new JWSInput(accessResRef.get().getAccessToken()).getContent(), AccessToken.class);
    Assert.assertEquals("Invalid nonce.", token.getNonce(), oauth1.getNonce());

    AccessToken refreshedToken = JsonSerialization.readValue(new JWSInput(refreshResRef.get().getAccessToken()).getContent(), AccessToken.class);
    Assert.assertEquals("Invalid nonce.", refreshedToken.getNonce(), oauth1.getNonce());

    if (userSessionId.get() == null) {
        userSessionId.set(token.getSessionState());
    }
}
 
Example 18
Source File: URLToolsClient.java    From MtgDesktopCompanion with GNU General Public License v3.0 4 votes vote down vote up
public URLToolsClient() {
	httpclient = HttpClients.custom().setUserAgent(MTGConstants.USER_AGENT).setRedirectStrategy(new LaxRedirectStrategy()).build();
	httpContext = new HttpClientContext();
	cookieStore = new BasicCookieStore();
	httpContext.setCookieStore(cookieStore);
}
 
Example 19
Source File: TestCookie.java    From httpclientutil with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws HttpProcessException {
		//登录地址
		String loginUrl = "https://passport.csdn.net/account/login";
		//C币查询
		String scoreUrl = "http://my.csdn.net/my/score";
		
		//定义cookie存储
		HttpClientContext context = new HttpClientContext();
		CookieStore cookieStore = new BasicCookieStore();
		context.setCookieStore(cookieStore);
		HttpConfig config =HttpConfig.custom().url(loginUrl).context(context);
		//获取参数
		String loginform = HttpClientUtil.get(config);//可以用.send(config)代替,但是推荐使用明确的get方法
		//System.out.println(loginform);
		System.out.println("获取登录所需参数");
		String lt = regex("\"lt\" value=\"([^\"]*)\"", loginform)[0];
		String execution = regex("\"execution\" value=\"([^\"]*)\"", loginform)[0];
		String _eventId = regex("\"_eventId\" value=\"([^\"]*)\"", loginform)[0];
		
		//组装参数
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("username", "用户名");
		map.put("password", "密码");
		map.put("lt", lt);
		map.put("execution", execution);
		map.put("_eventId", _eventId);

		//发送登录请求
		String result = HttpClientUtil.post(config.map(map));//可以用.send(config.method(HttpMethods.POST).map(map))代替,但是推荐使用明确的post方法
		//System.out.println(result);
		if(result.contains("帐号登录")){//如果有帐号登录,则说明未登录成功
			String errmsg = regex("\"error-message\">([^<]*)<", result)[0];
			System.err.println("登录失败:"+errmsg);
			return;
		}
		System.out.println("----登录成功----");
		
//		//打印参数,可以看到cookie里已经有值了。
//		cookieStore = context.getCookieStore();
//		for (Cookie cookie : cookieStore.getCookies()) {
//			System.out.println(cookie.getName()+"--"+cookie.getValue());
//		}
		
		//访问积分管理页面
		Header[] headers = HttpHeader.custom().userAgent("User-Agent: Mozilla/5.0").build();
		result = HttpClientUtil.post(config.url(scoreUrl).headers(headers));//可以用.send(config.url(scoreUrl).headers(headers))代替,但是推荐使用明确的post方法
		//获取C币
		String score = regex("\"last-img\"><span>([^<]*)<", result)[0];
		System.out.println("您当前有C币:"+score);
		
	}
 
Example 20
Source File: BasicTest.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void loginLogout() throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(new BasicCookieStore());

    // 1. first GET to fetch execution
    HttpGet get = new HttpGet(getLoginURL());
    get.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
    CloseableHttpResponse response = httpclient.execute(get, context);
    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    String responseBody = EntityUtils.toString(response.getEntity());
    int begin = responseBody.indexOf("name=\"execution\" value=\"");
    assertNotEquals(-1, begin);
    int end = responseBody.indexOf("\"/><input type=\"hidden\" name=\"_eventId\"");
    assertNotEquals(-1, end);

    String execution = responseBody.substring(begin + 24, end);
    assertNotNull(execution);

    // 2. then POST to authenticate
    List<NameValuePair> form = new ArrayList<>();
    form.add(new BasicNameValuePair("_eventId", "submit"));
    form.add(new BasicNameValuePair("execution", execution));
    form.add(new BasicNameValuePair("username", "mrossi"));
    form.add(new BasicNameValuePair("password", "password"));
    form.add(new BasicNameValuePair("geolocation", ""));

    HttpPost post = new HttpPost(getLoginURL());
    post.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
    post.setEntity(new UrlEncodedFormEntity(form, Consts.UTF_8));
    response = httpclient.execute(post, context);

    // 3. check authentication results
    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    Header[] cookie = response.getHeaders("Set-Cookie");
    assertNotNull(cookie);
    assertTrue(cookie.length > 0);
    assertEquals(1, Stream.of(cookie).filter(item -> item.getValue().startsWith("TGC")).count());

    String body = EntityUtils.toString(response.getEntity());
    assertTrue(body.contains("Log In Successful"));
    assertTrue(body.contains("have successfully logged into the Central Authentication Service"));

    // 4. logout
    HttpGet logout = new HttpGet(getLoginURL().replace("login", "logout"));
    logout.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
    response = httpclient.execute(logout, context);
    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    body = EntityUtils.toString(response.getEntity());
    assertTrue(body.contains("Logout successful"));
    assertTrue(body.contains("have successfully logged out of the Central Authentication Service"));
}