httpclient Yapi 模拟登录获取cookies

// https 忽略证书
		SSLContextBuilder builder = SSLContexts.custom();
		builder.loadTrustMaterial(null, new TrustStrategy() {
			@Override
			public boolean isTrusted(X509Certificate[] chain, String authType)
					throws CertificateException {
				return true;
			}
		});
		SSLContext sslContext = builder.build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				sslContext, new X509HostnameVerifier() {
			@Override
			public void verify(String host, SSLSocket ssl)
					throws IOException {
			}

			@Override
			public void verify(String host, X509Certificate cert)
					throws SSLException {
			}

			@Override
			public void verify(String host, String[] cns,
							   String[] subjectAlts) throws SSLException {
			}

			@Override
			public boolean verify(String s, SSLSession sslSession) {
				return true;
			}
		});

		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
				.<ConnectionSocketFactory> create().register("https", sslsf)
				.build();

		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
		CloseableHttpClient httpClient = HttpClients.custom()
				.setConnectionManager(cm).build();

		HttpPost httpPost = new HttpPost("https://yapixxx/api/user/login_by_ldap");
		httpPost.setHeader(new BasicHeader("Content-type", "application/x-www-form-urlencoded"));
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("email", "111"));
		list.add(new BasicNameValuePair("password", "12222"));
		httpPost.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
		HttpResponse response = httpClient.execute(httpPost);

		Header[] headers = response.getHeaders("Set-Cookie");
		HashMap<String, String> cookies = new HashMap<String, String>(2);
		for (Header header : headers) {
			if (header.getValue().contains("_yapi_token")) {
				String token = header.getValue()
						.substring(header.getValue().indexOf("=") + 1, header.getValue().indexOf(';'));
				cookies.put("_yapi_token", token);
			} else if (header.getValue().contains("_yapi_uid")) {
				String uid = header.getValue()
						.substring(header.getValue().indexOf("=") + 1, header.getValue().indexOf(';'));
				cookies.put("_yapi_uid", uid);
			}
		}
		System.out.println("Cookies"+ JSON.toJSONString(cookies));
发布了636 篇原创文章 · 获赞 58 · 访问量 47万+

猜你喜欢

转载自blog.csdn.net/wxb880114/article/details/104169258