use of org.apache.http.client.methods.HttpEntityEnclosingRequestBase in project openkit-android by OpenKit.
the class AsyncHttpClient method post.
/**
* 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 entity a raw {@link HttpEntity} to send with the request, for
* example, use this to send string/json/xml payloads to a server by
* passing a {@link org.apache.http.entity.StringEntity}.
* @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.
*/
public void post(Context context, String url, Header[] headers, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) {
HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPost(url), entity);
if (headers != null)
request.setHeaders(headers);
sendRequest(httpClient, httpContext, request, contentType, responseHandler, context);
}
use of org.apache.http.client.methods.HttpEntityEnclosingRequestBase in project openkit-android by OpenKit.
the class AsyncHttpClient method post.
/**
* 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.
*/
public void post(Context context, String url, Header[] headers, RequestParams params, String contentType, AsyncHttpResponseHandler responseHandler) {
HttpEntityEnclosingRequestBase request = new HttpPost(url);
if (params != null)
request.setEntity(paramsToEntity(params));
if (headers != null)
request.setHeaders(headers);
sendRequest(httpClient, httpContext, request, contentType, responseHandler, context);
}
use of org.apache.http.client.methods.HttpEntityEnclosingRequestBase in project disconf by knightliao.
the class HttpClientUtil method execute.
/**
* 处理具体代理请求执行, 入口方法
*
* @throws Exception
*/
public static <T> T execute(HttpRequestBase request, HttpResponseCallbackHandler<T> responseHandler) throws Exception {
CloseableHttpResponse httpclientResponse = null;
try {
if (LOGGER.isDebugEnabled()) {
Header[] headers = request.getAllHeaders();
for (Header header : headers) {
LOGGER.debug("request: " + header.getName() + "\t" + header.getValue());
}
}
httpclientResponse = httpclient.execute(request);
if (LOGGER.isDebugEnabled()) {
for (Header header : httpclientResponse.getAllHeaders()) {
LOGGER.debug("response header: {}\t{}", header.getName(), header.getValue());
}
}
// 填充状态码
int statusCode = httpclientResponse.getStatusLine().getStatusCode();
String requestBody = null;
if (request instanceof HttpEntityEnclosingRequestBase) {
HttpEntity requestEntity = ((HttpEntityEnclosingRequestBase) request).getEntity();
if (requestEntity != null) {
requestBody = EntityUtils.toString(requestEntity);
}
}
LOGGER.info("execute http request [{}], status code [{}]", requestBody, statusCode);
if (statusCode != 200) {
throw new Exception("execute request failed [" + requestBody + "], statusCode [" + statusCode + "]");
}
// 处理响应体
HttpEntity entity = httpclientResponse.getEntity();
if (entity != null && responseHandler != null) {
return responseHandler.handleResponse(requestBody, entity);
} else {
LOGGER.info("execute response [{}], response empty", requestBody);
}
return null;
} catch (Exception e) {
throw e;
} finally {
if (httpclientResponse != null) {
try {
httpclientResponse.close();
} catch (IOException e) {
}
}
}
}
use of org.apache.http.client.methods.HttpEntityEnclosingRequestBase in project RoboZombie by sahan.
the class EntityProcessor method process.
/**
* <p>Accepts the {@link InvocationContext} of an {@link HttpEntityEnclosingRequest} and inserts
* <b>the</b> request parameter which is annotated with @{@link Entity} into its body.</p>
*
* <p><b>Note</b> that it makes no sense to scope multiple entities within the same entity enclosing
* request (HTTP/1.1 <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">RFC-2616</a>).
* This processor fails for the following scenarios:</p>
*
* <ul>
* <li><b>No entity</b> was found in the endpoint method definition.</li>
* <li><b>Multiple entities</b> were found in the endpoint method definition.</li>
* <li>The annotated entity <b>failed to be resolved</b> to a matching {@link HttpEntity}.</li>
* </ul>
*
* <p>Parameter types are resolved to their {@link HttpEntity} as specified in
* {@link Entities#resolve(Object)}. If an attached @{@link Serialize} is discovered, the entity
* will be serialized using the specified serializer before translation to an {@link HttpEntity}.</p>
*
* <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
*
* @param context
* the {@link InvocationContext} which is used to retrieve the entity
* <br><br>
* @param request
* an instance of {@link HttpEntityEnclosingRequestBase} which allows the inclusion of an
* {@link HttpEntity} in its body
* <br><br>
* @return the same instance of {@link HttpRequestBase} which was given for processing entities
* <br><br>
* @throws RequestProcessorException
* if an {@link HttpEntityEnclosingRequestBase} was discovered and yet the entity failed to
* be resolved and inserted into the request body
* <br><br>
* @since 1.3.0
*/
//welcomes a ClassCastException on misuse of @Serialize(Custom.class)
@Override
//welcomes a ClassCastException on misuse of @Serialize(Custom.class)
@SuppressWarnings("unchecked")
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {
try {
if (request instanceof HttpEntityEnclosingRequestBase) {
List<Entry<Entity, Object>> entities = Metadata.onParams(Entity.class, context);
if (entities.isEmpty()) {
throw new MissingEntityException(context);
}
if (entities.size() > 1) {
throw new MultipleEntityException(context);
}
Object entity = entities.get(0).getValue();
Serialize metadata = (metadata = context.getRequest().getAnnotation(Serialize.class)) == null ? context.getEndpoint().getAnnotation(Serialize.class) : metadata;
if (metadata != null && !isDetached(context, Serialize.class)) {
//no restrictions on custom serializer types with @Serialize
@SuppressWarnings("rawtypes") AbstractSerializer serializer = (metadata.value() == UNDEFINED) ? Serializers.resolve(metadata.type()) : Serializers.resolve(metadata.value());
entity = serializer.run(context, entity);
}
HttpEntity httpEntity = Entities.resolve(entity);
((HttpEntityEnclosingRequestBase) request).setHeader(HttpHeaders.CONTENT_TYPE, ContentType.getOrDefault(httpEntity).getMimeType());
((HttpEntityEnclosingRequestBase) request).setEntity(httpEntity);
}
} catch (MissingEntityException mee) {
if (!(request instanceof HttpPost)) {
//allow leeway for POST requests
StringBuilder errorContext = new StringBuilder("It is imperative that this request encloses an entity.").append(" Identify exactly one entity by annotating an argument with @").append(Entity.class.getSimpleName());
throw new RequestProcessorException(errorContext.toString(), mee);
}
} catch (MultipleEntityException mee) {
//violates HTTP 1.1 specification, be more verbose
StringBuilder errorContext = new StringBuilder("This request is only able to enclose exactly one entity.").append(" Remove all @").append(Entity.class.getSimpleName()).append(" annotations except for a single entity which is identified by this URI. ");
throw new RequestProcessorException(errorContext.toString(), mee);
} catch (EntityResolutionFailedException erfe) {
//violates HTTP 1.1 specification, be more verbose
StringBuilder errorContext = new StringBuilder("This request cannot proceed without an enclosing entity.").append(" Ensure that the entity which is annotated with ").append(Entity.class.getSimpleName()).append(" complies with the supported types as documented in ").append(RequestUtils.class.getName()).append("#resolveHttpEntity(Object)");
throw new RequestProcessorException(errorContext.toString(), erfe);
} catch (Exception e) {
throw new RequestProcessorException(context, getClass(), e);
}
return request;
}
use of org.apache.http.client.methods.HttpEntityEnclosingRequestBase in project RoboZombie by sahan.
the class FormParamProcessor method process.
/**
* <p>Accepts the {@link InvocationContext} with an {@link HttpEntityEnclosingRequestBase} and
* creates a list of <a href="http://en.wikipedia.org/wiki/POST_(HTTP)#Use_for_submitting_web_forms">
* form-urlencoded</a> name-value pairs using arguments annotated with @{@link FormParam} and
* @{@link FormParams}. It's then inserted to the body of the request being processed.</p>
*
* <p><b>Note</b> that any {@link HttpRequestBase}s which aren't {@link HttpEntityEnclosingRequestBase}s
* will be ignored.</p>
*
* <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
*
* @param context
* the {@link InvocationContext} which is used to discover any annotated form parameters
* <br><br>
* @param request
* prefers an instance of {@link HttpPost} so as to conform with HTTP 1.1; however, other
* {@link HttpEntityEnclosingRequestBase}s will be entertained to allow compliance with
* unusual endpoint definitions (as long as they are {@link HttpEntityEnclosingRequestBase}s)
* <br><br>
* @return the same instance of {@link HttpRequestBase} which was given for processing form parameters
* <br><br>
* @throws RequestProcessorException
* if a form parameters failed to be created and inserted into the request body
* <br><br>
* @since 1.3.0
*/
@Override
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {
try {
if (request instanceof HttpEntityEnclosingRequestBase) {
List<NameValuePair> nameValuePairs = new LinkedList<NameValuePair>();
//add static name and value pairs
List<Param> constantFormParams = RequestUtils.findStaticFormParams(context);
for (Param param : constantFormParams) {
nameValuePairs.add(new BasicNameValuePair(param.name(), param.value()));
}
//add individual name and value pairs
List<Entry<FormParam, Object>> formParams = Metadata.onParams(FormParam.class, context);
for (Entry<FormParam, Object> entry : formParams) {
String name = entry.getKey().value();
Object value = entry.getValue();
if (!(value instanceof CharSequence)) {
StringBuilder errorContext = new StringBuilder().append("Form (url-encoded) parameters can only be of type ").append(CharSequence.class.getName()).append(". Please consider implementing CharSequence ").append("and providing a meaningful toString() representation for the ").append("<name> of the form parameter. ");
throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
}
nameValuePairs.add(new BasicNameValuePair(name, String.valueOf(value)));
}
//add batch name and value pairs (along with any static params)
List<Entry<FormParams, Object>> queryParamMaps = Metadata.onParams(FormParams.class, context);
for (Entry<FormParams, Object> entry : queryParamMaps) {
Param[] constantParams = entry.getKey().value();
if (constantParams != null && constantParams.length > 0) {
for (Param param : constantParams) {
nameValuePairs.add(new BasicNameValuePair(param.name(), param.value()));
}
}
Object map = entry.getValue();
if (!(map instanceof Map)) {
StringBuilder errorContext = new StringBuilder().append("@FormParams can only be applied on <java.util.Map>s. ").append("Please refactor the method to provide a Map of name and value pairs. ");
throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
}
Map<?, ?> nameAndValues = (Map<?, ?>) map;
for (Entry<?, ?> nameAndValue : nameAndValues.entrySet()) {
Object name = nameAndValue.getKey();
Object value = nameAndValue.getValue();
if (!(name instanceof CharSequence && (value instanceof CharSequence || value instanceof Collection))) {
StringBuilder errorContext = new StringBuilder().append("The <java.util.Map> identified by @FormParams can only contain mappings of type ").append("<java.lang.CharSequence, java.lang.CharSequence> or ").append("<java.lang.CharSequence, java.util.Collection<? extends CharSequence>>");
throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
}
if (value instanceof CharSequence) {
nameValuePairs.add(new BasicNameValuePair(((CharSequence) name).toString(), ((CharSequence) value).toString()));
} else {
//add multi-valued form params
Collection<?> multivalues = (Collection<?>) value;
for (Object multivalue : multivalues) {
if (!(multivalue instanceof CharSequence)) {
StringBuilder errorContext = new StringBuilder().append("Values for the <java.util.Map> identified by @FormParams can only contain collections ").append("of type java.util.Collection<? extends CharSequence>");
throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
}
nameValuePairs.add(new BasicNameValuePair(((CharSequence) name).toString(), ((CharSequence) multivalue).toString()));
}
}
}
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
urlEncodedFormEntity.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
return request;
} catch (Exception e) {
throw (e instanceof RequestProcessorException) ? (RequestProcessorException) e : new RequestProcessorException(context, getClass(), e);
}
}
Aggregations