下面列出了怎么用org.apache.http.HttpEntityEnclosingRequest的API类实例代码及写法,或者点击链接到github查看源代码。
public static HttpRequestHandler makeHttpHandler(
final int statusCode, final String body,
final List<String> requestBodies) {
return new HttpRequestHandler() {
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException,
IOException {
response.setStatusCode(statusCode);
response.setEntity(new StringEntity(body));
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
requestBodies.add(EntityUtils.toString(entity));
} else {
requestBodies.add("");
}
}
};
}
/**
* Sends a HTTP DELETE request with entity body to the specified URL.
*
* @param url Target endpoint URL
* @param headers Any HTTP headers that should be added to the request
* @return Returned HTTP response
* @throws IOException If an error occurs while making the invocation
*/
public HttpResponse doDeleteWithPayload(String url, final Map<String, String> headers,
final String payload, String contentType) throws IOException {
boolean zip = false;
HttpUriRequest request = new HttpDeleteWithEntity(url);
HTTPUtils.setHTTPHeaders(headers, request);
HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
//check if content encoding required
if (headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING))) {
zip = true;
}
EntityTemplate ent = new EntityTemplate(new EntityContentProducer(payload, zip));
ent.setContentType(contentType);
if (zip) {
ent.setContentEncoding("gzip");
}
entityEncReq.setEntity(ent);
return httpclient.execute(request);
}
@Override
public String toString() {
HttpUriRequest request = getRawRequest();
StringBuilder outBuffer = new StringBuilder();
String endl = "\n";
outBuffer.append("ApacheHttpRequest Info").append(endl);
outBuffer.append("type: HttpUriRequest").append(endl);
outBuffer.append("uri: ").append(request.getURI().toString()).append(endl);
outBuffer.append("headers: ");
Arrays.stream(request.getAllHeaders()).forEach(header ->
outBuffer.append("[").append(header.getName()).append(":").append(header.getValue()).append("] ")
);
outBuffer.append(endl);
if (request instanceof HttpEntityEnclosingRequest) {
try {
String body = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity());
outBuffer.append("body: ").append(body).append(endl);
} catch (IOException e) {
outBuffer.append("body: ").append(e.getMessage()).append(endl);
}
}
return outBuffer.toString();
}
@Override
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context)
throws ProtocolException
{
final String method = request.getRequestLine().getMethod();
HttpUriRequest redirect = super.getRedirect(request, response, context);
if (HttpPost.METHOD_NAME.equalsIgnoreCase(method))
{
HttpPost httpPostRequest = new HttpPost(redirect.getURI());
if (request instanceof HttpEntityEnclosingRequest)
{
httpPostRequest.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
}
return httpPostRequest;
}
return redirect;
}
/**
* Send a HTTP POST request to the specified URL
*
* @param url Target endpoint URL
* @param headers Any HTTP headers that should be added to the request
* @param payload Content payload that should be sent
* @param contentType Content-type of the request
* @return Returned HTTP response
* @throws IOException If an error occurs while making the invocation
*/
public HttpResponse doPost(String url, final Map<String, String> headers,
final String payload, String contentType) throws IOException {
HttpUriRequest request = new HttpPost(url);
setHeaders(headers, request);
HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));
EntityTemplate ent = new EntityTemplate(new ContentProducer() {
public void writeTo(OutputStream outputStream) throws IOException {
OutputStream out = outputStream;
if (zip) {
out = new GZIPOutputStream(outputStream);
}
out.write(payload.getBytes());
out.flush();
out.close();
}
});
ent.setContentType(contentType);
if (zip) {
ent.setContentEncoding("gzip");
}
entityEncReq.setEntity(ent);
return client.execute(request);
}
public void handle(HttpRequest request, HttpResponse response, HttpContext arg2) throws HttpException, IOException {
if (request.getRequestLine().getMethod().equals("POST")) {
// Retrieve the POST content
HttpEntityEnclosingRequest post = (HttpEntityEnclosingRequest) request;
byte[] entityContent = EntityUtils.toByteArray(post.getEntity());
String content = new String(entityContent, Charset.forName("UTF-8"));
// Execute the request
final String json = RequestHandler.handle(content);
// Return the response
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write(json);
writer.flush();
}
});
response.setStatusCode(HttpStatus.SC_OK);
body.setContentType("application/json; charset=UTF-8");
response.setEntity(body);
}
}
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] bufferedOutput)
throws IOException {
HttpComponentsClientHttpRequest.addHeaders(this.httpRequest, headers);
if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest;
HttpEntity requestEntity = new NByteArrayEntity(bufferedOutput);
entityEnclosingRequest.setEntity(requestEntity);
}
HttpResponseFutureCallback callback = new HttpResponseFutureCallback(this.httpRequest);
Future<HttpResponse> futureResponse = this.httpClient.execute(this.httpRequest, this.httpContext, callback);
return new ClientHttpResponseFuture(futureResponse, callback);
}
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Decide about retry #" + executionCount + " for exception " + exception.getMessage());
}
if (executionCount >= _maxRetryCount) {
// Do not retry if over max retry count
return false;
} else if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
} else if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
// Retry if the request is considered idempotent
return idempotent;
}
/**
* Ctor.
*
* @param request The http request
* @throws IllegalStateException if the request's payload cannot be read
*/
PayloadOf(final HttpRequest request) {
super(() -> {
try {
final JsonObject body;
if (request instanceof HttpEntityEnclosingRequest) {
body = Json.createReader(
((HttpEntityEnclosingRequest) request).getEntity()
.getContent()
).readObject();
} else {
body = Json.createObjectBuilder().build();
}
return body;
} catch (final IOException ex) {
throw new IllegalStateException(
"Cannot read request payload", ex
);
}
});
}
/**
* Prepares a HttpUriRequest to be sent.
*
* @param headers HTTP headers to be set as a MAP <Header name, Header value>
* @param payload Final payload to be sent
* @param contentType Content-type (i.e application/json)
* @param request HttpUriRequest request to be prepared
*/
private void prepareRequest(Map<String, String> headers, final String payload, String contentType,
HttpUriRequest request) {
HTTPUtils.setHTTPHeaders(headers, request);
HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));
EntityTemplate ent = new EntityTemplate(new ContentProducer() {
public void writeTo(OutputStream outputStream) throws IOException {
OutputStream out = outputStream;
if (zip) {
out = new GZIPOutputStream(outputStream);
}
out.write(payload.getBytes());
out.flush();
out.close();
}
});
ent.setContentType(contentType);
if (zip) {
ent.setContentEncoding("gzip");
}
entityEncReq.setEntity(ent);
}
/**
* Ctor.
*
* @param request The http request
* @throws IllegalStateException if the request's payload cannot be read
*/
public StringPayloadOf(final HttpRequest request) {
try {
if (request instanceof HttpEntityEnclosingRequest) {
this.stringPayload = EntityUtils.toString(
((HttpEntityEnclosingRequest) request).getEntity()
);
} else {
this.stringPayload = "";
}
} catch (final IOException ex) {
throw new IllegalStateException(
"Cannot read request payload", ex
);
}
}
private static HttpRequest handleRequest(HttpHost host, HttpRequest request, NetInfo data) {
RequestLine requestLine = request.getRequestLine();
if (requestLine != null) {
String uri = requestLine.getUri();
int i = (uri != null) && (uri.length() >= 10) && (uri.substring(0, 10).indexOf("://") >= 0) ? 1 : 0;
if ((i == 0) && (uri != null) && (host != null)) {
String uriFromHost = host.toURI().toString();
data.setURL(uriFromHost + ((uriFromHost.endsWith("/")) || (uri.startsWith("/")) ? "" : "/") + uri);
} else if (i != 0) {
data.setURL(uri);
}
}
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
if (entityRequest.getEntity() != null) {
entityRequest.setEntity(new AopHttpRequestEntity(entityRequest.getEntity(), data));
}
return entityRequest;
}
return request;
}
private void configureSolrClientsForKerberos() throws PermanentBackendException {
String kerberosConfig = System.getProperty("java.security.auth.login.config");
if(kerberosConfig == null) {
throw new PermanentBackendException("Unable to configure kerberos for solr client. System property 'java.security.auth.login.config' is not set.");
}
logger.debug("Using kerberos configuration file located at '{}'.", kerberosConfig);
try(Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) {
SolrHttpClientBuilder kb = krbBuild.getBuilder();
HttpClientUtil.setHttpClientBuilder(kb);
HttpRequestInterceptor bufferedEntityInterceptor = new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
if(request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest enclosingRequest = ((HttpEntityEnclosingRequest) request);
HttpEntity requestEntity = enclosingRequest.getEntity();
enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
}
}
};
HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);
HttpRequestInterceptor preemptiveAuth = new PreemptiveAuth(new KerberosScheme());
HttpClientUtil.addRequestInterceptor(preemptiveAuth);
}
}
@Test
public void testEncodedUriSigner() throws Exception {
HttpEntityEnclosingRequest request =
new BasicHttpEntityEnclosingRequest("GET", "/foo-2017-02-25%2Cfoo-2017-02-26/_search?a=b");
request.setEntity(new StringEntity("I'm an entity"));
request.addHeader("foo", "bar");
request.addHeader("content-length", "0");
HttpCoreContext context = new HttpCoreContext();
context.setTargetHost(HttpHost.create("localhost"));
createInterceptor().process(request, context);
assertEquals("bar", request.getFirstHeader("foo").getValue());
assertEquals("wuzzle", request.getFirstHeader("Signature").getValue());
assertNull(request.getFirstHeader("content-length"));
assertEquals("/foo-2017-02-25%2Cfoo-2017-02-26/_search", request.getFirstHeader("resourcePath").getValue());
}
public boolean retryRequest(IOException exception, int executionCount,
HttpContext context) {
// 设置恢复策略,在发生异常时候将自动重试3次
if (executionCount >= 3) {
// 如果连接次数超过了最大值则停止重试
return false;
}
if (exception instanceof NoHttpResponseException) {
// 如果服务器连接失败重试
return true;
}
if (exception instanceof SSLHandshakeException) {
// 不要重试ssl连接异常
return false;
}
HttpRequest request = (HttpRequest) context
.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
if (!idempotent) {
// 重试,如果请求是考虑幂等
return true;
}
return false;
}
private byte[] serializeContent(HttpRequest request) {
if (!(request instanceof HttpEntityEnclosingRequest)) {
return new byte[]{};
}
final HttpEntityEnclosingRequest entityWithRequest = (HttpEntityEnclosingRequest) request;
HttpEntity entity = entityWithRequest.getEntity();
if (entity == null) {
return new byte[]{};
}
try {
// Buffer non-repeatable entities
if (!entity.isRepeatable()) {
entityWithRequest.setEntity(new BufferedHttpEntity(entity));
}
return EntityUtils.toByteArray(entityWithRequest.getEntity());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static String getHTTPRequestTrace(HttpRequest request) {
StringBuilder sb = new StringBuilder();
sb.append(request.getRequestLine());
sb.append('\n');
for (Header h : request.getAllHeaders()) {
sb.append(h.getName()).append(": ").append(h.getValue()).append('\n');
}
sb.append('\n');
// Check if the request is POST or PUT
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest r = (HttpEntityEnclosingRequest) request;
HttpEntity e = r.getEntity();
if (e != null) {
appendHttpEntity(sb, e);
}
}
return sb.toString();
}
/**
* Get delay time before next retry.
*
* @param method The current HTTP method being executed.
* @param exception The client/service exception from the failed request.
* @param attempt The number of times the current request has been attempted.
* @param retryPolicy The retryPolicy being used.
* @return The deley time before next retry.
*/
protected long getDelayBeforeNextRetryInMillis(HttpRequestBase method, BceClientException exception, int attempt,
RetryPolicy retryPolicy) {
int retries = attempt - 1;
int maxErrorRetry = retryPolicy.getMaxErrorRetry();
// Immediately fails when it has exceeds the max retry count.
if (retries >= maxErrorRetry) {
return -1;
}
// Never retry on requests containing non-repeatable entity
if (method instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) method).getEntity();
if (entity != null && !entity.isRepeatable()) {
logger.debug("Entity not repeatable, stop retrying");
return -1;
}
}
return Math.min(retryPolicy.getMaxDelayInMillis(),
retryPolicy.getDelayBeforeNextRetryInMillis(exception, retries));
}
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] bufferedOutput)
throws IOException {
HttpComponentsClientHttpRequest.addHeaders(this.httpRequest, headers);
if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest;
HttpEntity requestEntity = new NByteArrayEntity(bufferedOutput);
entityEnclosingRequest.setEntity(requestEntity);
}
final HttpResponseFutureCallback callback = new HttpResponseFutureCallback();
final Future<HttpResponse> futureResponse =
this.httpClient.execute(this.httpRequest, this.httpContext, callback);
return new ClientHttpResponseFuture(futureResponse, callback);
}
/**
* Send a HTTP DELETE request with entity body to the specified URL
*
* @param url Target endpoint URL
* @param headers Any HTTP headers that should be added to the request
* @return Returned HTTP response
* @throws IOException If an error occurs while making the invocation
*/
public HttpResponse doDeleteWithPayload(String url, final Map<String, String> headers,
final String payload, String contentType) throws IOException {
boolean zip = false;
HttpUriRequest request = new HttpDeleteWithEntity(url);
setHeaders(headers, request);
HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
//check if content encoding required
if (headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING))) {
zip = true;
}
EntityTemplate ent = new EntityTemplate(new EntityContentProducer(payload, zip));
ent.setContentType(contentType);
if (zip) {
ent.setContentEncoding("gzip");
}
entityEncReq.setEntity(ent);
return client.execute(request);
}
public void requestReceived(HttpRequest request) {
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
try {
InputStream in = entity.getContent();
String inputString = IOUtils.toString(in, "UTF-8");
payload = inputString;
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public String getCharacterEncoding() {
if (delegate instanceof HttpEntityEnclosingRequest) {
return ((HttpEntityEnclosingRequest) delegate).getEntity().getContentEncoding().getValue();
} else {
return null;
}
}
@Override
public int getContentLength() {
if (delegate instanceof HttpEntityEnclosingRequest) {
return (int) ((HttpEntityEnclosingRequest) delegate).getEntity().getContentLength();
} else {
return 0;
}
}
@Test
void shouldBeSafeAgainstCallingWithBodyTwice() throws IOException {
final HttpEntityEnclosingRequest delegate = post("/");
delegate.setEntity(new StringEntity("Hello, world!", UTF_8));
final LocalRequest unit = unit(delegate);
assertThat(new String(unit.withBody().withBody().getBody(), UTF_8), is("Hello, world!"));
}
@Override
public void setBody(final Body body) {
if (request instanceof HttpEntityEnclosingRequest) {
final HttpEntityEnclosingRequest enclosing = (HttpEntityEnclosingRequest) request;
enclosing.setEntity(new StreamingHttpEntity(body));
} else {
throw new IllegalStateException(getMethodValue() + " doesn't support a body");
}
}
@Test
void testGetRedirect() throws ProtocolException
{
mockHeader();
when(statusLine.getStatusCode()).thenReturn(STATUS_CODE);
when(httpResponse.getStatusLine()).thenReturn(statusLine);
HttpEntityEnclosingRequest httpRequest = new HttpPost(URI);
StringEntity requestStringEntity = new StringEntity("{key:value}", StandardCharsets.UTF_8);
httpRequest.setEntity(requestStringEntity);
HttpEntityEnclosingRequest actualRedirect = (HttpEntityEnclosingRequest) redirectStrategy
.getRedirect(httpRequest, httpResponse, httpContext);
assertEquals(REDIRECT_URI, actualRedirect.getRequestLine().getUri());
assertEquals(requestStringEntity, actualRedirect.getEntity());
}
@Override
public void process(HttpRequest request, HttpContext context)
{
byte[] body = null;
String mimeType = null;
if (request instanceof HttpEntityEnclosingRequest)
{
HttpEntityEnclosingRequest requestWithBody = (HttpEntityEnclosingRequest) request;
HttpEntity entity = requestWithBody.getEntity();
if (entity != null)
{
mimeType = Optional.ofNullable(ContentType.getLenient(entity))
.map(ContentType::getMimeType)
.orElseGet(() -> getMimeType(requestWithBody.getAllHeaders()));
try (ByteArrayOutputStream baos = new ByteArrayOutputStream((int) entity.getContentLength()))
{
// https://github.com/apache/httpcomponents-client/commit/09cefc2b8970eea56d81b1a886d9bb769a48daf3
entity.writeTo(baos);
body = baos.toByteArray();
}
catch (IOException e)
{
LOGGER.error("Error is occurred at HTTP message parsing", e);
}
}
}
RequestLine requestLine = request.getRequestLine();
String attachmentTitle = String.format("Request: %s %s", requestLine.getMethod(), requestLine.getUri());
attachApiMessage(attachmentTitle, request.getAllHeaders(), body, mimeType, -1);
}
@Test
void testNoHttpRequestBodyIsAttached()
{
HttpEntityEnclosingRequest httpRequest = mockHttpEntityEnclosingRequest(new Header[] {},
mock(HttpEntity.class));
testNoHttpRequestBodyIsAttached(httpRequest, empty());
}
@Test
void testHttpRequestBodyAttachingIsFailed() throws IOException
{
HttpEntity httpEntity = mock(HttpEntity.class);
when(httpEntity.getContentType()).thenReturn(null);
IOException ioException = new IOException();
doThrow(ioException).when(httpEntity).writeTo(any(ByteArrayOutputStream.class));
HttpEntityEnclosingRequest httpRequest = mockHttpEntityEnclosingRequest(new Header[] { mock(Header.class) },
httpEntity);
testNoHttpRequestBodyIsAttached(httpRequest,
equalTo(List.of(error(ioException, "Error is occurred at HTTP message parsing"))));
}
private void testHttpRequestIsAttachedSuccessfully(Header[] allRequestHeaders, Header entityContentTypeHeader)
throws IOException
{
HttpEntity httpEntity = mock(HttpEntity.class);
when(httpEntity.getContentType()).thenReturn(entityContentTypeHeader);
HttpEntityEnclosingRequest httpRequest = mockHttpEntityEnclosingRequest(allRequestHeaders, httpEntity);
testHttpRequestIsAttachedSuccessfully(httpRequest);
verify(httpEntity).getContentLength();
verify(httpEntity).writeTo(any(ByteArrayOutputStream.class));
}