Search in sources :

Example 96 with HttpEntity

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;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) Entity(com.lonepulse.robozombie.annotation.Entity) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) Serialize(com.lonepulse.robozombie.annotation.Serialize) HttpEntity(org.apache.http.HttpEntity) EntityResolutionFailedException(com.lonepulse.robozombie.util.EntityResolutionFailedException) EntityResolutionFailedException(com.lonepulse.robozombie.util.EntityResolutionFailedException) Entry(java.util.Map.Entry)

Example 97 with HttpEntity

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());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpEntity(org.apache.http.HttpEntity) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DataOutputStream(java.io.DataOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) GZIPInputStream(java.util.zip.GZIPInputStream) HttpHost(org.apache.http.HttpHost) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) PredefinedBAOS(com.androidquery.util.PredefinedBAOS) BufferedOutputStream(java.io.BufferedOutputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Date(java.util.Date) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 98 with HttpEntity

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);
        }
    });
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) JSONObject(org.json.JSONObject) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) JSONObject(org.json.JSONObject) AjaxStatus(com.androidquery.callback.AjaxStatus)

Example 99 with HttpEntity

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"));
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) JSONObject(org.json.JSONObject) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.JSONObject) AjaxStatus(com.androidquery.callback.AjaxStatus)

Example 100 with HttpEntity

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;
}
Also used : HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException)

Aggregations

HttpEntity (org.apache.http.HttpEntity)518 HttpResponse (org.apache.http.HttpResponse)185 HttpGet (org.apache.http.client.methods.HttpGet)152 IOException (java.io.IOException)144 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)105 Test (org.junit.Test)93 HttpPost (org.apache.http.client.methods.HttpPost)84 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)83 InputStream (java.io.InputStream)71 ArrayList (java.util.ArrayList)69 Header (org.apache.http.Header)64 StatusLine (org.apache.http.StatusLine)61 URI (java.net.URI)58 NameValuePair (org.apache.http.NameValuePair)58 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)58 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)58 HttpClient (org.apache.http.client.HttpClient)55 StringEntity (org.apache.http.entity.StringEntity)51 InputStreamReader (java.io.InputStreamReader)44 BufferedReader (java.io.BufferedReader)41