下面列出了org.apache.http.client.methods.HttpEntityEnclosingRequestBase#setEntity() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Method posts request payload
*
* @param request
* @param payload
* @return
*/
protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload, HttpHost proxy) {
HttpResponse response = null;
boolean ok = false;
int tryCount = 0;
while (!ok) {
try {
tryCount++;
HttpClient httpclient = new DefaultHttpClient();
if(proxy != null) {
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
request.setEntity(new ByteArrayEntity(payload));
log(request);
response = httpclient.execute(request);
ok = true;
} catch(IOException ioe) {
if (tryCount <= retryCount) {
ok = false;
} else {
throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
}
}
}
return response;
}
public XmlRequest(CloseableHttpClient client, URI uri, Document requestDoc) {
super(client, uri, getMethod(requestDoc));
this.requestDoc = requestDoc;
logger.debug(Log.REQUEST, uri.toString());
// if requestDoc is null then use GET
// this is only applicable for WSDL
if (method == HttpMethod.GET) {
requestText = null;
request = new HttpGet(uri);
}
// otherwise use POST
else {
requestText = XmlFormatter.format(requestDoc);
HttpEntity requestEntity = new StringEntity(requestText, ContentType.TEXT_XML);
HttpEntityEnclosingRequestBase httpPost = new HttpPost(uri);
httpPost.setEntity(requestEntity);
request = httpPost;
}
}
/**
* 根据请求信息创建HttpEntityEnclosingRequestBase.
*
* @param cls 类型Class
* @param url URL
* @param headers Http请求头信息
* @param params 请求参数列表
* @return HttpEntityEnclosingRequestBase
*/
protected HttpEntityEnclosingRequestBase createEntityBase(final Class<? extends HttpEntityEnclosingRequestBase> cls, final String url,
final Map<String, String> headers, final Map<String, String> params) {
try {
final HttpEntityEnclosingRequestBase entityBase = ReflectUtils.newInstance(cls, url);
if (!CollectionUtils.isEmpty(headers)) {
headers.forEach((key, value) -> entityBase.addHeader(key, value));
}
final List<NameValuePair> pairs = covertParams2Nvps(params);
entityBase.setEntity(new UrlEncodedFormEntity(pairs, this.conf.getCharset()));
return entityBase;
} catch (final Throwable e) {
throw new HttpClientInvokeException(e.getMessage(), e);
}
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
private HttpRequestBase wrapEntity(Request<?> request,
HttpEntityEnclosingRequestBase entityEnclosingRequest,
String encodedParams) throws FakeIOException {
if (HttpMethodName.POST == request.getHttpMethod()) {
/*
* If there isn't any payload content to include in this request,
* then try to include the POST parameters in the query body,
* otherwise, just use the query string. For all AWS Query services,
* the best behavior is putting the params in the request body for
* POST requests, but we can't do that for S3.
*/
if (request.getContent() == null && encodedParams != null) {
entityEnclosingRequest.setEntity(ApacheUtils.newStringEntity(encodedParams));
} else {
entityEnclosingRequest.setEntity(new RepeatableInputStreamRequestEntity(request));
}
} else {
/*
* We should never reuse the entity of the previous request, since
* reading from the buffered entity will bypass reading from the
* original request content. And if the content contains InputStream
* wrappers that were added for validation-purpose (e.g.
* Md5DigestCalculationInputStream), these wrappers would never be
* read and updated again after AmazonHttpClient resets it in
* preparation for the retry. Eventually, these wrappers would
* return incorrect validation result.
*/
if (request.getContent() != null) {
HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
if (request.getHeaders().get(HttpHeaders.CONTENT_LENGTH) == null) {
entity = ApacheUtils.newBufferedHttpEntity(entity);
}
entityEnclosingRequest.setEntity(entity);
}
}
return entityEnclosingRequest;
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
private void setEntityIfGiven(HttpEntityEnclosingRequestBase request, Object entity) {
if (entity != null) {
if (entity instanceof File) {
request.setEntity(new FileEntity((File) entity));
} else {
request.setEntity(new StringEntity((String) entity, Charset.defaultCharset()));
}
}
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
/**
* 将请求参数设置到HttpEntity中
*
* @param httpRequest
* @param request
*/
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
/**
* Method posts request payload
*
* @param request
* @param payload
* @return
*/
protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload) {
HttpResponse response = null;
try {
log(request);
HttpClient httpclient = new DefaultHttpClient();
request.setEntity(new ByteArrayEntity(payload));
response = httpclient.execute(request);
log(response);
} catch(IOException ioe) {
throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
}
return response;
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
private static void setEntityIfNonEmptyBody(
HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
@AfterClass
public static void tearDownClass() throws Exception {
URIBuilder builder = new URIBuilder().setScheme("http")
.setHost("127.0.0.1").setPort(9200)
.setPath("/metric_metadata/metrics/_query");
HttpEntityEnclosingRequestBase delete = new HttpEntityEnclosingRequestBase() {
@Override
public String getMethod() {
return "DELETE";
}
};
delete.setURI(builder.build());
String deletePayload = "{\"query\":{\"match_all\":{}}}";
HttpEntity entity = new NStringEntity(deletePayload, ContentType.APPLICATION_JSON);
delete.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(delete);
if(response.getStatusLine().getStatusCode() != 200)
{
System.out.println("Couldn't delete index after running tests.");
}
else {
System.out.println("Successfully deleted index after running tests.");
}
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
@Override
protected void receiveContent(InputStream content) {
if (content == null) {
return;
}
try {
URI uri = get();
if (uri == null) {
throw new IllegalStateException("No uri for output");
}
HttpUriRequest method = null;
HttpEntityEnclosingRequestBase receiver = null;
if (isUsePut()) {
HttpPut putter = new HttpPut(uri);
method = putter;
receiver = putter;
} else {
HttpPost poster = new HttpPost(uri);
method = poster;
receiver = poster;
}
InputStreamEntity entity = new InputStreamEntity(content, -1);
receiver.setEntity(entity);
HttpResponse response = client.execute(method, getContext());
content.close();
StatusLine status = response.getStatusLine();
if (!method.isAborted()) {
method.abort();
}
if (status.getStatusCode() >= 300) {
throw new MarkLogicIOException("Could not write to "+uri.toString()+": "+status.getReasonPhrase());
}
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public void setRequestBody(HttpEntityEnclosingRequestBase req, Object body) {
StringEntity entity = new StringEntity(body.toString(), "utf-8");
req.setEntity(entity);
}
@Override
public void setRequestBody(HttpEntityEnclosingRequestBase req, Object body) {
StringEntity entity = new StringEntity(body.toString(), "utf-8");
req.setEntity(entity);
}
@Override
public void setRequestBody(HttpEntityEnclosingRequestBase req, Object body) {
StringEntity entity = new StringEntity(body.toString(), "utf-8");
req.setEntity(entity);
}
/**
* Perform a HTTP POST request and track the Android Context which initiated the request. Set
* headers only for this request
*
* @param context the Android Context which initiated the request.
* @param url the URL to send the request to.
* @param headers set headers only for this request
* @param params additional POST parameters to send with the request.
* @param contentType the content type of the payload you are sending, for example
* application/json if sending a json payload.
* @param responseHandler the response handler instance that should handle the response.
* @return RequestHandle of future request process
*/
public RequestHandle post(Context context, String url, Header[] headers, RequestParams params, String contentType,
ResponseHandlerInterface responseHandler) {
HttpEntityEnclosingRequestBase request = new HttpPost(getURI(url));
if (params != null) request.setEntity(paramsToEntity(params, responseHandler));
if (headers != null) request.setHeaders(headers);
return sendRequest(httpClient, httpContext, request, contentType,
responseHandler, context);
}