下面列出了怎么用org.apache.http.client.fluent.Request的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public JsonResult serviceDiscovery(ServiceValue serviceValue) {
JsonResult jsonResult = new JsonResult();
String url = Program.CONFIG_VALUE.getWebsiteUrl() + Constants.DISCOVERY_SERVICE_SITE_URI;
String reqJson = JacksonUtils.toJson(serviceValue);
try {
StringEntity entity = new StringEntity(reqJson);
String result;
if (url.startsWith("https")) {
result = HttpsClientUtil.doPostByStringEntity(url, entity, Constants.DEFAULT_CHARSET);
} else {
result = Request.Post(url).setHeader("Content-type", "application/json")
.body(entity).socketTimeout(5000).connectTimeout(5000)
.execute().returnContent().asString();
}
WebsitResult response = JacksonUtils.toObject(result, WebsitResult.class);
if (!Constants.SUCCESS.equals(response.getCode())) {
logger.error("request:" + reqJson + ",result:" + result);
}
jsonResult.setRet(Integer.parseInt(response.getCode()));
jsonResult.setMsg(response.getMessage());
} catch (Exception e) {
logger.error(e);
}
return jsonResult;
}
@Test
public void call_round_robin_lb_multiple_endpoints() throws Exception {
wireMockRule.stubFor(get("/api1").willReturn(ok()));
wireMockRule.stubFor(get("/api2").willReturn(ok()));
Request request = Request.Get("http://localhost:8082/api");
int calls = 20;
for(int i = 0 ; i < calls ; i++) {
HttpResponse response = request.execute().returnResponse();
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
wireMockRule.verify((i / 2) + 1, getRequestedFor(urlEqualTo("/api" + (i%2 + 1))));
}
wireMockRule.verify(calls / 2, getRequestedFor(urlPathEqualTo("/api1")));
wireMockRule.verify(calls / 2, getRequestedFor(urlPathEqualTo("/api2")));
}
@Override
protected AccessTokenData requestAccessTokenData(AuthorizationData authorizationData) throws NotificationException {
try {
String accessTokenUrl = getAccessTokenUrl(authorizationData.getAuthorizationCode()).get();
log.trace("Access token URL is {}", accessTokenUrl);
String response = Request.Get(accessTokenUrl).execute().returnContent().asString();
JsonParser jsonParser = new JsonParser();
JsonObject json = jsonParser.parse(response).getAsJsonObject();
ImmutableMap.Builder<String, String> result = ImmutableMap.builder();
if (!json.get("ok").getAsBoolean()) {
throw new NotificationException(json.get("error").getAsString());
}
result.put("teamId", json.get("team_id").getAsString());
result.put("teamName", json.get("team_name").getAsString());
return new AccessTokenData(json.get("access_token").getAsString(), result.build());
} catch (IOException e) {
throw new NotificationException(e.getMessage(), e);
}
}
public static String postRequestAsString(String url, String request)
throws UicdDeviceHttpConnectionResetException {
logger.info("post request to xmldumper:" + url);
String ret = "";
Response response = null;
try {
response = Request.Post(url)
.body(new StringEntity(request))
.execute();
ret = response.returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
logger.severe(e.getMessage());
// See comments in getRequestAsString
if (CONNECTION_RESET_KEYWORDS_LIST.stream().parallel().anyMatch(e.getMessage()::contains)) {
throw new UicdDeviceHttpConnectionResetException(e.getMessage());
}
}
logger.info("return from xmldumper:" + ret);
return ret;
}
@Test
public void shouldRespondWithNotImplemented() throws Exception {
wireMockRule.stubFor(any(urlEqualTo("/team/my_team"))
.willReturn(aResponse().withStatus(HttpStatus.SC_NOT_IMPLEMENTED)));
Request request = Request.Get("http://localhost:8082/test/my_team");
// A little bit of reflection to set an unknown HTTP method since the fluent API does not allow it.
Field requestField = request.getClass().getDeclaredField("request");
requestField.setAccessible(true);
Field methodField = requestField.get(request).getClass().getDeclaredField("method");
methodField.setAccessible(true);
methodField.set(requestField.get(request), "unkown-method");
Response response = request.execute();
HttpResponse returnResponse = response.returnResponse();
assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, returnResponse.getStatusLine().getStatusCode());
wireMockRule.verify(anyRequestedFor(urlPathEqualTo("/team/my_team")));
}
/**
* Get Access token of the user.
*
* @return an access token of the user
*/
public String getGogsAccessToken() {
String resp;
String sha1 = null;
Executor executor = getExecutor();
try {
resp = executor.execute(
Request.Get(this.getGogsUrl() + "/api/v1/users/" + this.gogsServer_user + "/tokens")
).returnContent().toString();
JSONArray jsonArray = JSONArray.fromObject(resp);
if (!jsonArray.isEmpty()) {
sha1 = ((JSONObject) jsonArray.get(0)).getString("sha1");
}
} catch (IOException e) { }
return sha1;
}
@Test
public void simple_request_ssl() throws Exception {
wireMockRule.stubFor(get("/team/my_team").willReturn(ok()));
// First call is calling an endpoint where trustAll is defined to true, no need for truststore => 200
HttpResponse response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("trustAll is defined to true, no need for truststore => 200", HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Second call is calling an endpoint where trustAll is defined to false, without truststore => 502
response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("trustAll is defined to false, without truststore => 502", HttpStatus.SC_BAD_GATEWAY, response.getStatusLine().getStatusCode());
// Third call is calling an endpoint where trustAll is defined to false, with truststore => 200
response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("trustAll is defined to false, with truststore => 200", HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Check that the stub has been successfully invoked by the gateway
wireMockRule.verify(2, getRequestedFor(urlPathEqualTo("/team/my_team")));
}
@Test
@RunAsClient
public void testJavaxJsonb() throws IOException {
Dog dog = new Dog();
dog.name = "Falco";
dog.age = 4;
dog.bitable = false;
Jsonb jsonb = JsonbBuilder.create();
String json = jsonb.toJson(dog);
String response = Request.Post("http://localhost:8080/").body(new StringEntity(json))
.execute().returnContent().asString().trim();
Dog dog2 = jsonb.fromJson(response, Dog.class);
assertThat(dog2.name).isEqualTo(dog.name);
assertThat(dog2.age).isEqualTo(dog.age);
assertThat(dog2.bitable).isTrue();
}
public static void main(String[] args) throws Exception {
// URL白名单组件测试
CheckURL urlCheck = new CheckURL();
String[] urlWList = {"joychou.com", "joychou.me"};
Boolean ret = urlCheck.checkUrlWlist("http://test.joychou.org", urlWList);
System.out.println(ret);
// SSRF组件测试
SSRF check = new SSRF();
String url = "http://127.0.0.1.xip.io";
ret = check.checkSSRF(url);
if (ret){
String con = Request.Get(url).execute().returnContent().toString();
System.out.println(con);
}
else {
System.out.println("Bad boy. The url is illegal");
}
// 获取客户端IP测试
}
@Test
public void simple_request_client_auth() throws Exception {
wireMockRule.stubFor(get("/team/my_team").willReturn(ok()));
// First call is calling an HTTPS endpoint without ssl configuration => 502
HttpResponse response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("without ssl configuration => 502", HttpStatus.SC_BAD_GATEWAY, response.getStatusLine().getStatusCode());
// Second call is calling an endpoint where trustAll = false, without truststore => 502
response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("trustAll = false, without truststore => 502", HttpStatus.SC_BAD_GATEWAY, response.getStatusLine().getStatusCode());
// Third call is calling an endpoint where trustAll = false, with truststore => 200
response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("trustAll = false, with truststore => 200", HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Fourth call is calling an endpoint where trustAll = true, without truststore => 200
response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("trustAll = true, with keystore => 200", HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Check that the stub has been successfully invoked by the gateway
wireMockRule.verify(2, getRequestedFor(urlPathEqualTo("/team/my_team")));
}
static Result<Job, JsonObject> submitJob(ApplicationBundle bundle, JsonObject jco) throws IOException {
UploadedApplicationBundle uab = (UploadedApplicationBundle) bundle;
JsonObject body = new JsonObject();
body.addProperty("application", uab.getBundleId());
body.addProperty("preview", false);
body.add("jobConfigurationOverlay", jco);
final AbstractStreamsConnection conn = bundle.instance().connection();
Request postBundle = Request.Post(bundle.instance().self() + "/jobs");
postBundle.addHeader(AUTH.WWW_AUTH_RESP, conn.getAuthorization());
postBundle.body(new StringEntity(body.toString(), ContentType.APPLICATION_JSON));
JsonObject response = requestGsonResponse(conn.executor, postBundle);
Job job = Job.create(bundle.instance(), response.toString());
if (!response.has(SubmissionResultsKeys.JOB_ID))
response.addProperty(SubmissionResultsKeys.JOB_ID, job.getId());
return new ResultImpl<Job, JsonObject>(true, job.getId(),
() -> job, response);
}
@Test
@RunAsClient
public void hello() throws IOException, GeneralSecurityException {
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
.build();
try (CloseableHttpClient httpClient = HttpClients.custom()
.setSSLContext(sslContext)
.build()) {
String response = Executor.newInstance(httpClient)
.execute(Request.Get("https://localhost:8443/"))
.returnContent().asString();
assertThat(response).contains("Hello on port 8443, secure: true");
}
}
protected boolean delete(String deleteJobUrl) throws IOException {
boolean rc = false;
String sReturn = "";
Request request = Request
.Delete(deleteJobUrl)
.addHeader(AUTH.WWW_AUTH_RESP, getAuthorization())
.useExpectContinue();
Response response = executor.execute(request);
HttpResponse hResponse = response.returnResponse();
int rcResponse = hResponse.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == rcResponse) {
sReturn = EntityUtils.toString(hResponse.getEntity());
rc = true;
} else {
rc = false;
}
traceLog.finest("Request: [" + deleteJobUrl + "]");
traceLog.finest(rcResponse + ": " + sReturn);
return rc;
}
@Override
protected AccessTokenData requestAccessTokenData(AuthorizationData authorizationData) throws NotificationException {
try {
String authorizationCode = authorizationData.getAuthorizationCode();
String response =
Request.Post(getAccessTokenUrl(authorizationCode).get()).bodyForm(
Form.form()
.add("client_id", getClientId())
.add("client_secret", getClientSecret())
.add("code", authorizationCode)
.add("grant_type", "authorization_code").build())
.execute().returnContent().asString();
JsonObject json = new JsonParser().parse(response).getAsJsonObject();
String accessToken = json.get("access_token").getAsString();
String tokenType = json.get("token_type").getAsString();
return new AccessTokenData(accessToken, ImmutableMap.of("tokenType", tokenType));
} catch (IOException e) {
throw new NotificationException(e);
}
}
@Override
public Optional<InputStream> recursiveMetaDataAsJson(InputStream inputStream, org.apache.james.mailbox.model.ContentType contentType) {
try {
ContentType httpContentType = ContentType.create(contentType.mimeType().asString(),
contentType.charset()
.map(Charset::name)
.orElse(null));
return Optional.ofNullable(
Request.Put(recursiveMetaData)
.socketTimeout(tikaConfiguration.getTimeoutInMillis())
.bodyStream(inputStream, httpContentType)
.execute()
.returnContent()
.asStream());
} catch (IOException e) {
LOGGER.warn("Failing to call Tika for content type {}", contentType, e);
return Optional.empty();
}
}
public static List<Map> getJobList(String resourceManagerUrl, Optional<String> beginTime) {
try {
String json;
if (beginTime.isPresent()) {
long currentTimeMillis = System.currentTimeMillis();
long startedTimeBegin = currentTimeMillis - Long.valueOf(beginTime.get());
json = Request.Get(resourceManagerUrl + "/ws/v1/cluster/apps?startedTimeBegin=" + startedTimeBegin)
.execute().returnContent().asString(UTF_8);
} else {
json = Request.Get(resourceManagerUrl + "/ws/v1/cluster/apps")
.execute().returnContent().asString(UTF_8);
}
return jsonToMaps(json);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private <U> U execute(URISupplier<URI> uriSupplier, MappingFunction<byte[], U> responseMapper, Supplier<U> notFoundMapper) {
try {
URI uri = uriSupplier.get();
Request request = Request.Get(uri);
HttpResponse response = request.execute().returnResponse();
if (response.getStatusLine().getStatusCode() == 200) {
byte[] returnJson = EntityUtils.toByteArray(response.getEntity());
return responseMapper.apply(returnJson);
} else if (response.getStatusLine().getStatusCode() == 404) {
return notFoundMapper.get();
} else if (response.getStatusLine().getStatusCode() == 400) {
throw new IllegalArgumentException("Bad Request");
} else {
throw new QueryExecutionException("Something went wrong, status code: " + response.getStatusLine().getStatusCode());
}
} catch (URISyntaxException | IOException e) {
throw new ConnectionException("Error creating connection", e);
}
}
@Test
public void call_get_query_accent() throws Exception {
wireMockRule.stubFor(
get(urlPathEqualTo("/team/my_team"))
.willReturn(
ok()
.withBody("{{request.query.q}}")
.withTransformers("response-template")));
String query = "poupée";
URI target = new URIBuilder("http://localhost:8082/test/my_team")
.addParameter("q", query)
.build();
HttpResponse response = Request.Get(target).execute().returnResponse();
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
String responseContent = StringUtils.copy(response.getEntity().getContent());
assertEquals(query, responseContent);
wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/team/my_team")));
}
/**
* A method to wait for the availability of the Gogs server
*
* @param retries the number of times we should try to connect
* @param retryDelay the number of seconds to wait between tentatives
* @throws TimeoutException thrown when number of retries was exhausted
* @throws InterruptedException thrown when the wait has been interrupted
*/
void waitForServer(int retries, int retryDelay) throws TimeoutException, InterruptedException {
String testUrl = this.getGogsUrl() + "/";
for (int i = 0; i < retries; i++) {
int status;
try {
status = Request.Get(testUrl)
.execute().returnResponse().getStatusLine().getStatusCode();
} catch (IOException e) {
TimeUnit.SECONDS.sleep(retryDelay);
continue;
}
if (status == 200) {
return;
} else {
TimeUnit.SECONDS.sleep(retryDelay);
}
}
throw new TimeoutException("Timeout waiting for availability of " + testUrl);
}
@RunAsClient
@Test
public void tokenInCookieHeader() throws Exception {
String response = Request.Get("http://localhost:8080/mpjwt/default-group/secured")
.setHeader("Cookie", "a=b;jwt=" + createToken("User"))
.execute().returnContent().asString();
assertThat(response).isEqualTo("User");
}
/**
* multipart/mixed post请求
*
* @param url
* @param paramsList
* @return
* @throws Exception
*/
public static String doPostByMultipartMixed(String url, List<CustomHttpParams> paramsList) throws Exception {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--";
String LINEND = "\r\n";
if (null == paramsList || paramsList.isEmpty()) {
return null;
}
byte[] totalByte = null;
String data = null;
int size = paramsList.size();
for (int i = 0; i < size; i++) {
CustomHttpParams httpParam = paramsList.get(i);
Map<String, Object> map = httpParam.getMap();
byte[] bt = httpParam.getBt();
String joinMapStr = joinParams(map);
byte[] mapBt = joinMapStr.getBytes("UTF-8");
if (0 == i) {
data = PREFIX + BOUNDARY + LINEND + "Content-Type:application/octet-stream" + LINEND + "Content-Disposition:param;" + joinMapStr + LINEND + "Content-Length:" + mapBt.length + LINEND + LINEND;
totalByte = byteMerge(data.getBytes(), bt);
} else {
data = LINEND + PREFIX + BOUNDARY + LINEND + "Content-Type:application/octet-stream" + LINEND + "Content-Disposition:param;" + joinMapStr + LINEND + "Content-Length:" + mapBt.length + LINEND + LINEND;
totalByte = byteMerge(totalByte, data.getBytes());
totalByte = byteMerge(totalByte, bt);
}
}
data = LINEND + PREFIX + BOUNDARY + PREFIX;
totalByte = byteMerge(totalByte, data.getBytes());
NameValuePair nameValuePair = new BasicNameValuePair("boundary", BOUNDARY);
HttpEntity entity = Request.Post(url).connectTimeout(5000)
.bodyByteArray(totalByte, ContentType.create("multipart/mixed", nameValuePair))
.execute().returnResponse().getEntity();
return EntityUtils.toString(entity, "utf-8");
}
public String doGet(String url) {
try {
return Request.Get(url).execute().returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@RunAsClient
@Test
public void keycloakToken() throws Exception {
InputStream stream = getClass().getResourceAsStream("/keycloakToken.json");
String json = new BufferedReader(new InputStreamReader(stream))
.lines().collect(Collectors.joining("\n"));
String response = Request.Get("http://localhost:8080/mpjwt/keycloak/secured")
.setHeader("Authorization", "Bearer " + createTokenFromJson(json))
.execute().returnContent().asString();
assertThat(response).isEqualTo("user1");
}
/**
* 设置代理
* @param request
* @param hostName
* @param port
* @param schemeName
* @return
*/
private Request buildProxy(Request request, String hostName, Integer port, String schemeName) {
if(StringUtils.isNotEmpty(hostName) && port != null) {
//设置代理
if (StringUtils.isEmpty(schemeName)) {
schemeName = HttpHost.DEFAULT_SCHEME_NAME;
}
request.viaProxy(new HttpHost(hostName, port, schemeName));
}
return request;
}
@Test
public void large_body_with_content_length() throws Exception {
String mockContent = StringUtils.copy(
getClass().getClassLoader().getResourceAsStream("case2/response_content.json"));
stubFor(post(urlEqualTo("/team/my_team"))
.willReturn(
ok()
.withBody(mockContent)
.withHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)));
Request request = Request.Post("http://localhost:8082/test/my_team").bodyString(mockContent, ContentType.APPLICATION_JSON);
HttpResponse response = request.execute().returnResponse();
System.out.println(wireMockRule.findAllUnmatchedRequests().size());
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
String content = StringUtils.copy(response.getEntity().getContent());
assertEquals(652051, content.length());
assertEquals(content, content);
assertNull(response.getFirstHeader(HttpHeaders.CONTENT_LENGTH));
assertNotNull(response.getFirstHeader(HttpHeaders.TRANSFER_ENCODING));
assertEquals(HttpHeadersValues.TRANSFER_ENCODING_CHUNKED, response.getFirstHeader(HttpHeaders.TRANSFER_ENCODING).getValue());
verify(postRequestedFor(urlEqualTo("/team/my_team"))
.withRequestBody(equalTo(mockContent)));
}
private Request buildRequestWithHeaders(Request request, Map<String, String> headers) {
for (val entry : headers.entrySet()) {
val key = entry.getKey();
val value = entry.getValue();
request.addHeader(key, value);
}
return request;
}
@Test
public void shouldNotFollowRedirect() throws Exception {
wireMockRule.stubFor(get("/redirect").willReturn(permanentRedirect("http://localhost:" + wireMockRule.port() + "/final")));
HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();
Request request = Request.Get("http://localhost:8082/api/redirect");
Response response = Executor.newInstance(client).execute(request);
HttpResponse returnResponse = response.returnResponse();
assertEquals(HttpStatus.SC_MOVED_PERMANENTLY, returnResponse.getStatusLine().getStatusCode());
wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/redirect")));
wireMockRule.verify(0, getRequestedFor(urlPathEqualTo("/final")));
}
@RunAsClient
@Test
public void shouldGetHtmlForAllowedUser() throws Exception {
String response = Request.Get("http://localhost:8080/mpjwt/parameterized-paths/my/hello/admin")
.setHeader("Authorization", "Bearer " + createToken("MappedRole"))
.setHeader("Accept", MediaType.TEXT_HTML)
.execute().returnContent().asString();
Assert.assertEquals("Admin accessed hello", response);
}
@Test
public void simple_request_client_auth() throws Exception {
wireMockRule.stubFor(get("/team/my_team").willReturn(ok()));
// First call is calling an HTTPS endpoint without ssl configuration => 502
HttpResponse response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("without ssl configuration => 502",
HttpStatus.SC_BAD_GATEWAY, response.getStatusLine().getStatusCode());
// Second call is calling an endpoint where trustAll = false, without keystore => 502
response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("trustAll = false, without keystore => 200",
HttpStatus.SC_BAD_GATEWAY, response.getStatusLine().getStatusCode());
// Third call is calling an endpoint where trustAll = true, with keystore => 200
response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("trustAll = true, with keystore => 200",
HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Fourth call is calling an endpoint where trustAll = false, with truststore and keystore => 200
response = Request.Get("http://localhost:8082/test/my_team").execute().returnResponse();
assertEquals("trustAll = false, with truststore and keystore => 200",
HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Check that the stub has been successfully invoked by the gateway
wireMockRule.verify(2, getRequestedFor(urlPathEqualTo("/team/my_team")));
}
private SagaResponse on(Request request) {
try {
HttpResponse httpResponse = request.execute().returnResponse();
int statusCode = httpResponse.getStatusLine().getStatusCode();
String content = IOUtils.toString(new InputStreamReader(httpResponse.getEntity().getContent()));
if (statusCode >= 200 && statusCode < 300) {
return new SuccessfulSagaResponse(content);
}
throw new TransportFailedException("The remote service returned with status code " + statusCode
+ ", reason " + httpResponse.getStatusLine().getReasonPhrase()
+ ", and content " + content);
} catch (IOException e) {
throw new TransportFailedException("Network Error", e);
}
}