下面列出了怎么用org.apache.http.client.fluent.Response的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
public SoapRawClientResponse callSoapService(InputStream xmlFile) throws InternalBusinessException {
SoapRawClientResponse rawSoapResponse = new SoapRawClientResponse();
LOGGER.debug("Calling SoapService with POST on Apache HTTP-Client and configured URL: {}", soapServiceUrl);
try {
Response httpResponseContainer = Request
.Post(soapServiceUrl)
.bodyStream(xmlFile, contentTypeTextXmlUtf8())
.addHeader("SOAPAction", "\"" + soapAction + "\"")
.execute();
HttpResponse httpResponse = httpResponseContainer.returnResponse();
rawSoapResponse.setHttpStatusCode(httpResponse.getStatusLine().getStatusCode());
rawSoapResponse.setHttpResponseBody(XmlUtils.parseFileStream2Document(httpResponse.getEntity().getContent()));
} catch (Exception exception) {
throw new InternalBusinessException("Some Error accured while trying to Call SoapService for test: " + exception.getMessage());
}
return rawSoapResponse;
}
@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")));
}
@Test
public void call_weighted_lb_multiple_endpoints() throws Exception {
wireMockRule.stubFor(get(urlEqualTo("/api1")).willReturn(ok()));
wireMockRule.stubFor(get(urlEqualTo("/api2")).willReturn(ok()));
Request request = Request.Get("http://localhost:8082/api");
int calls = 10;
for(int i = 0 ; i < calls ; i++) {
Response response = request.execute();
HttpResponse returnResponse = response.returnResponse();
assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());
}
wireMockRule.verify(3, getRequestedFor(urlPathEqualTo("/api1")));
wireMockRule.verify(7, getRequestedFor(urlPathEqualTo("/api2")));
}
@Test
public void no_content_without_chunked_encoding_transfer() throws Exception {
stubFor(post(urlEqualTo("/team/my_team")).willReturn(ok()));
Request request = Request.Post("http://localhost:8082/test/my_team")
.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
Response response = request.execute();
HttpResponse returnResponse = response.returnResponse();
assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());
// Set chunk mode in request but returns raw because of the size of the content
assertEquals(null, returnResponse.getFirstHeader("X-Forwarded-Transfer-Encoding"));
String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
assertEquals(0, responseContent.length());
verify(postRequestedFor(urlEqualTo("/team/my_team"))
.withoutHeader(HttpHeaders.TRANSFER_ENCODING)
.withHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE, new EqualToPattern(MediaType.APPLICATION_JSON)));
}
@Test
public void get_no_content_with_chunked_encoding_transfer() throws Exception {
stubFor(get(urlEqualTo("/team/my_team")).willReturn(ok()));
Request request = Request.Get("http://localhost:8082/test/my_team")
.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
Response response = request.execute();
HttpResponse returnResponse = response.returnResponse();
assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());
// Set chunk mode in request but returns raw because of the size of the content
assertEquals(null, returnResponse.getFirstHeader("X-Forwarded-Transfer-Encoding"));
String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
assertEquals(0, responseContent.length());
verify(getRequestedFor(urlEqualTo("/team/my_team"))
.withoutHeader(HttpHeaders.TRANSFER_ENCODING)
.withHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE, new EqualToPattern(MediaType.APPLICATION_JSON)));
}
@Test
public void get_no_content_with_chunked_encoding_transfer_and_content_type() throws Exception {
stubFor(get(urlEqualTo("/team/my_team")).willReturn(ok()));
Request request = Request.Get("http://localhost:8082/test/my_team")
.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
Response response = request.execute();
HttpResponse returnResponse = response.returnResponse();
assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());
// Set chunk mode in request but returns raw because of the size of the content
assertEquals(null, returnResponse.getFirstHeader("X-Forwarded-Transfer-Encoding"));
String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
assertEquals(0, responseContent.length());
verify(getRequestedFor(urlEqualTo("/team/my_team"))
.withHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE, new EqualToPattern(MediaType.APPLICATION_JSON)));
}
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;
}
/**
* Sends a request to Orion
*
* @param ctxElement
* The context element
* @param path
* the path from the context broker that determines which "operation"will be executed
* @param responseClazz
* The class expected for the response
* @return The object representing the JSON answer from Orion
* @throws OrionConnectorException
* if a communication exception happens, either when contacting the context broker at
* the given address, or obtaining the answer from it.
*/
private <E, T> T sendRequestToOrion(E ctxElement, String path, Class<T> responseClazz) {
String jsonEntity = gson.toJson(ctxElement);
log.debug("Send request to Orion: {}", jsonEntity);
Request req = Request.Post(this.orionAddr.toString() + path)
.addHeader("Accept", APPLICATION_JSON.getMimeType())
.bodyString(jsonEntity, APPLICATION_JSON).connectTimeout(5000).socketTimeout(5000);
Response response;
try {
response = req.execute();
} catch (IOException e) {
throw new OrionConnectorException("Could not execute HTTP request", e);
}
HttpResponse httpResponse = checkResponse(response);
T ctxResp = getOrionObjFromResponse(httpResponse, responseClazz);
log.debug("Sent to Orion. Obtained response: {}", httpResponse);
return ctxResp;
}
@Test
// @AgentRunner.TestConfig(verbose = true)
public void httpServiceTest(final MockTracer tracer) throws Exception {
final Response response = Request.Get("http://" + HOST + ":" + PORT + "/").execute();
assertEquals(response.returnResponse().getStatusLine().getStatusCode(), 503);
assertEquals(1, tracer.finishedSpans().size());
}
private String getJSON() throws IOException {
String url = "http://music.163.com/weapi/v3/playlist/detail";
List<BasicNameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("params", "kJMudgZJvK8p8STuuxRpkUvO71Enw4C9y91PBkVTv2SMVnWG30eDKK1iAPcXnEah"));
params.add(new BasicNameValuePair("encSecKey", "d09b0b95b7d5b4e68aa7a16d6177d3f00a78bfa013ba59f309d41f18a2b4ea066cdea7863866b6283f403ddcd3bfb51f73f8ad3c6818269ceabff934a645196faf7a9aae0edde6e232b279fd495140e6252503291cf819eabbd9f3373648775201a70f179b7981d627257d3bba5a5e1b99d0732ce3e898db3614d82bcbe1a6a8"));
Response response = Request.Post(url)
.bodyForm(params)
.execute();
return response.returnContent().asString(Charset.forName("utf-8"));
}
private <T> T executeRequest(String requestPath, Map<String, String> queryParameters, TypeReference reference,
RequestMethod method) throws IOException {
ValidationUtils.checkArgument(!closed, "View already closed");
URIBuilder builder =
new URIBuilder().setHost(serverHost).setPort(serverPort).setPath(requestPath).setScheme("http");
queryParameters.forEach(builder::addParameter);
// Adding mandatory parameters - Last instants affecting file-slice
timeline.lastInstant().ifPresent(instant -> builder.addParameter(LAST_INSTANT_TS, instant.getTimestamp()));
builder.addParameter(TIMELINE_HASH, timeline.getTimelineHash());
String url = builder.toString();
LOG.info("Sending request : (" + url + ")");
Response response;
int timeout = 1000 * 300; // 5 min timeout
switch (method) {
case GET:
response = Request.Get(url).connectTimeout(timeout).socketTimeout(timeout).execute();
break;
case POST:
default:
response = Request.Post(url).connectTimeout(timeout).socketTimeout(timeout).execute();
break;
}
String content = response.returnContent().asString();
return mapper.readValue(content, reference);
}
@Test
@RunAsClient
public void testGettingView() throws IOException {
Response response = Request.Get(baseUrl.toString() + "/hello").execute();
Content content = response.returnContent();
assertThat(content.asString(), containsString("Hello World!"));
}
@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")));
}
private void trustForBlobId(String blobId, String username) throws Exception {
Response tokenGenerationResponse = Request.Post(baseUri(mainStepdefs.jmapServer).setPath("/download/" + blobId).build())
.addHeader("Authorization", userStepdefs.authenticate(username).asString())
.execute();
String serializedAttachmentAccessToken = tokenGenerationResponse.returnContent().asString();
attachmentAccessTokens.put(
new AttachmentAccessTokenKey(username, blobId),
AttachmentAccessToken.from(
serializedAttachmentAccessToken,
blobId));
}
@Test
public void containerShouldBeReachableOnExposedPort() throws IOException, URISyntaxException {
Response response = Request.Get(new URIBuilder()
.setScheme("http")
.setHost(container.getHostIp())
.setPort(container.getMappedPort(80)).build())
.execute();
assertThat(response.returnResponse().getStatusLine().getStatusCode())
.isEqualTo(200);
}
public static AccessToken doAuthenticate(URIBuilder uriBuilder, Username username, String password) throws ClientProtocolException, IOException, URISyntaxException {
String continuationToken = getContinuationToken(uriBuilder, username);
Response response = postAuthenticate(uriBuilder, password, continuationToken);
return AccessToken.of(
JsonPath.parse(response.returnContent().asString())
.read("accessToken"));
}
private static Response postAuthenticate(URIBuilder uriBuilder, String password, String continuationToken) throws ClientProtocolException, IOException, URISyntaxException {
return Request.Post(uriBuilder.setPath("/authentication").build())
.bodyString("{\"token\": \"" + continuationToken + "\", \"method\": \"password\", \"password\": \"" + password + "\"}",
ContentType.APPLICATION_JSON)
.setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType())
.execute();
}
private static String getContinuationToken(URIBuilder uriBuilder, Username username) throws ClientProtocolException, IOException, URISyntaxException {
Response response = Request.Post(uriBuilder.setPath("/authentication").build())
.bodyString("{\"username\": \"" + username.asString() + "\", \"clientName\": \"Mozilla Thunderbird\", \"clientVersion\": \"42.0\", \"deviceName\": \"Joe Blogg’s iPhone\"}",
ContentType.APPLICATION_JSON)
.setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType())
.execute();
return JsonPath.parse(response.returnContent().asString())
.read("continuationToken");
}
private static InputStream rawStreamingGet(Executor executor,
String auth, String url) throws IOException {
TRACE.fine("HTTP GET: " + url);
String accepted =
ContentType.APPLICATION_OCTET_STREAM.getMimeType()
+ ","
+ "application/x-compressed";
Request request = Request
.Get(url)
.addHeader("accept",accepted)
.useExpectContinue();
if (null != auth) {
request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
}
Response response = executor.execute(request);
HttpResponse hResponse = response.returnResponse();
int rcResponse = hResponse.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == rcResponse) {
return hResponse.getEntity().getContent();
} else {
// all other errors...
String httpError = "HttpStatus is " + rcResponse + " for url " + url;
throw new RESTException(rcResponse, httpError);
}
}
static Toolkit uploadToolkit(StreamsBuildService connection, File path) throws IOException {
// Make sure it is a directory
if (! path.isDirectory()) {
throw new IllegalArgumentException("The specified toolkit path '" + path.toString() + "' is not a directory.");
}
// Make sure it contains toolkit.xml
File toolkit = new File(path, "toolkit.xml");
if (! toolkit.isFile()) {
throw new IllegalArgumentException("The specified toolkit path '" + path.toString() + "' is not a toolkit.");
}
String toolkitsURL = connection.getToolkitsURL();
Request post = Request.Post(toolkitsURL);
post.addHeader(AUTH.WWW_AUTH_RESP, connection.getAuthorization());
post.bodyStream(DirectoryZipInputStream.fromPath(path.toPath()), ContentType.create("application/zip"));
Response response = connection.getExecutor().execute(post);
HttpResponse httpResponse = response.returnResponse();
int statusCode = httpResponse.getStatusLine().getStatusCode();
// TODO The API is supposed to return CREATED, but there is a bug and it
// returns OK. When the bug is fixed, change this to accept only OK
if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
String message = EntityUtils.toString(httpResponse.getEntity());
throw RESTException.create(statusCode, message);
}
HttpEntity entity = httpResponse.getEntity();
try (Reader r = new InputStreamReader(entity.getContent())) {
JsonObject jresponse = new Gson().fromJson(r, JsonObject.class);
EntityUtils.consume(entity);
List<Toolkit> toolkitList = Toolkit.createToolkitList(connection, jresponse);
// We expect a list of zero or one element.
if (toolkitList.size() == 0) {
return null;
}
return toolkitList.get(0);
}
}
static boolean cancelJob(Instance instance, String jobId) throws IOException {
Request deleteJob = Request.Delete(instance.self() + "/jobs/" + jobId);
Response response = instance.connection().executor.execute(deleteJob);
// TODO - error handling
return true;
}
private <T> HttpResponse checkResponse(Response response) {
HttpResponse httpResponse;
try {
httpResponse = response.returnResponse();
} catch (IOException e) {
throw new OrionConnectorException("Could not obtain HTTP response", e);
}
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new OrionConnectorException(
"Failed with HTTP error code : " + httpResponse.getStatusLine().getStatusCode());
}
return httpResponse;
}
/**
* Runs the provided request and returns the response.
*/
public Response execute(Request request) throws IOException {
return executor.execute(request);
}
@Test
@RunAsClient
public void shouldGetMetricsWithoutAcceptHeadersSet() throws IOException {
Response response = Request.Get("http://localhost:8080/metrics").execute();
assertThat(response.returnResponse().getStatusLine().getStatusCode()).isEqualTo(200);
}
/**
* Gets a JSON response to an HTTP request call
*/
static JsonObject requestGsonResponse(Executor executor, Request request) throws IOException {
request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
Response response = executor.execute(request);
return gsonFromResponse(response.returnResponse());
}
/**
* Gets a JSON response to an HTTP request call
*/
static JsonObject requestGsonResponse(Executor executor, Request request) throws IOException {
request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
Response response = executor.execute(request);
return gsonFromResponse(response.returnResponse());
}
/**
* Gets a JSON response to an HTTP request call
*/
static JsonObject requestGsonResponse(Executor executor, Request request) throws IOException {
request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
Response response = executor.execute(request);
return gsonFromResponse(response.returnResponse());
}
static String requestTextResponse(Executor executor, Request request) throws IOException {
request.addHeader("accept", ContentType.TEXT_PLAIN.getMimeType());
Response response = executor.execute(request);
return textFromResponse(response.returnResponse());
}