use of org.apache.http.HttpEntity 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.HttpEntity in project androidquery by androidquery.
the class AbstractAjaxCallback method httpDo.
private void httpDo(HttpUriRequest hr, String url, AjaxStatus status) throws ClientProtocolException, IOException {
DefaultHttpClient client = getClient();
if (proxyHandle != null) {
proxyHandle.applyProxy(this, hr, client);
}
if (AGENT != null) {
hr.addHeader("User-Agent", AGENT);
} else if (AGENT == null && GZIP) {
hr.addHeader("User-Agent", "gzip");
}
if (headers != null) {
for (String name : headers.keySet()) {
hr.addHeader(name, headers.get(name));
}
}
if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
hr.addHeader("Accept-Encoding", "gzip");
}
if (ah != null) {
ah.applyToken(this, hr);
}
String cookie = makeCookie();
if (cookie != null) {
hr.addHeader("Cookie", cookie);
}
HttpParams hp = hr.getParams();
if (proxy != null)
hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
if (timeout > 0) {
hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
}
if (!redirect) {
hp.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
}
HttpContext context = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
request = hr;
if (abort) {
throw new IOException("Aborted");
}
if (SIMULATE_ERROR) {
throw new IOException("Simulated Error");
}
HttpResponse response = null;
try {
//response = client.execute(hr, context);
response = execute(hr, client, context);
} catch (HttpHostConnectException e) {
//if proxy is used, automatically retry without proxy
if (proxy != null) {
AQUtility.debug("proxy failed, retrying without proxy");
hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
//response = client.execute(hr, context);
response = execute(hr, client, context);
} else {
throw e;
}
}
byte[] data = null;
String redirect = url;
int code = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
String error = null;
HttpEntity entity = response.getEntity();
File file = null;
File tempFile = null;
if (code < 200 || code >= 300) {
InputStream is = null;
try {
if (entity != null) {
is = entity.getContent();
byte[] s = toData(getEncoding(entity), is);
error = new String(s, "UTF-8");
AQUtility.debug("error", error);
}
} catch (Exception e) {
AQUtility.debug(e);
} finally {
AQUtility.close(is);
}
} else {
HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
redirect = currentHost.toURI() + currentReq.getURI();
int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));
OutputStream os = null;
InputStream is = null;
try {
file = getPreFile();
if (file == null) {
os = new PredefinedBAOS(size);
} else {
//file.createNewFile();
tempFile = makeTempFile(file);
os = new BufferedOutputStream(new FileOutputStream(tempFile));
}
is = entity.getContent();
boolean gzip = "gzip".equalsIgnoreCase(getEncoding(entity));
if (gzip) {
is = new GZIPInputStream(is);
}
int contentLength = (int) entity.getContentLength();
//AQUtility.debug("gzip response", entity.getContentEncoding());
copy(is, os, contentLength, tempFile, file);
if (file == null) {
data = ((PredefinedBAOS) os).toByteArray();
} else {
if (!file.exists() || file.length() == 0) {
file = null;
}
}
} finally {
AQUtility.close(is);
AQUtility.close(os);
}
}
AQUtility.debug("response", code);
if (data != null) {
AQUtility.debug(data.length, url);
}
status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file).client(client).context(context).headers(response.getAllHeaders());
}
use of org.apache.http.HttpEntity in project androidquery by androidquery.
the class AjaxLoadingActivity method async_post_entity.
/*
public void async_post2(){
String url = "your url";
//get your byte array or file
byte[] data = new byte[1000];
Map<String, Object> params = new HashMap<String, Object>();
//put your post params
params.put("paramName", data);
AjaxCallback<byte[]> cb = new AjaxCallback<byte[]>() {
@Override
public void callback(String url, byte[] data, AjaxStatus status) {
System.out.println(data);
System.out.println(status.getCode() + ":" + status.getError());
}
};
cb.url(url).type(byte[].class);
//set Content-Length header
cb.params(params).header("Content-Length", Integer.toString(data.length));
cb.async(this);
}
*/
public void async_post_entity() throws UnsupportedEncodingException {
String url = "http://search.twitter.com/search.json";
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("q", "androidquery"));
HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
Map<String, Object> params = new HashMap<String, Object>();
params.put(AQuery.POST_ENTITY, entity);
aq.progress(R.id.progress).ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
showResult(json, status);
}
});
}
use of org.apache.http.HttpEntity in project androidquery by androidquery.
the class AQueryAsyncTest method testAjaxPostRaw.
public void testAjaxPostRaw() throws UnsupportedEncodingException {
String url = "http://www.androidquery.com/p/doNothing";
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("q", "androidquery"));
HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
Map<String, Object> params = new HashMap<String, Object>();
params.put(AQuery.POST_ENTITY, entity);
aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject jo, AjaxStatus status) {
done(url, jo, status);
}
});
waitAsync();
JSONObject jo = (JSONObject) result;
assertNotNull(jo);
assertNotNull(jo.opt("params"));
assertEquals("POST", jo.optString("method"));
}
use of org.apache.http.HttpEntity in project jstorm by alibaba.
the class HttpClientService method parseResponse.
private String parseResponse(String url, HttpResponse httpResponse) throws Exception, IOException {
int status = httpResponse.getStatusLine().getStatusCode();
if (status != 200) {
String errorMsg = "Error occurs in calling acl service: " + url + ", with status:" + status;
throw new Exception(errorMsg);
}
HttpEntity entry = httpResponse.getEntity();
String response = EntityUtils.toString(entry, "UTF-8");
return response;
}
Aggregations