Search in sources :

Example 31 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project clutchandroid by clutchio.

the class ClutchAPIClient method sendRequest.

private static void sendRequest(String url, boolean post, JSONObject payload, String version, final ClutchAPIResponseHandler responseHandler) {
    BasicHeader[] headers = { new BasicHeader("X-App-Version", version), new BasicHeader("X-UDID", ClutchUtils.getUDID()), new BasicHeader("X-API-Version", VERSION), new BasicHeader("X-App-Key", appKey), new BasicHeader("X-Bundle-Version", versionName), new BasicHeader("X-Platform", "Android") };
    StringEntity entity = null;
    try {
        entity = new StringEntity(payload.toString());
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "Could not encode the JSON payload and attach it to the request: " + payload.toString());
        return;
    }
    HttpRequestBase request = null;
    if (post) {
        request = new HttpPost(url);
        ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
        request.setHeaders(headers);
    } else {
        request = new HttpGet(url);
    }
    class StatusCodeAndResponse {

        public int statusCode;

        public String response;

        public StatusCodeAndResponse(int statusCode, String response) {
            this.statusCode = statusCode;
            this.response = response;
        }
    }
    new AsyncTask<HttpRequestBase, Void, StatusCodeAndResponse>() {

        @Override
        protected StatusCodeAndResponse doInBackground(HttpRequestBase... requests) {
            try {
                HttpResponse resp = client.execute(requests[0]);
                HttpEntity entity = resp.getEntity();
                InputStream inputStream = entity.getContent();
                ByteArrayOutputStream content = new ByteArrayOutputStream();
                int readBytes = 0;
                byte[] sBuffer = new byte[512];
                while ((readBytes = inputStream.read(sBuffer)) != -1) {
                    content.write(sBuffer, 0, readBytes);
                }
                inputStream.close();
                String response = new String(content.toByteArray());
                content.close();
                return new StatusCodeAndResponse(resp.getStatusLine().getStatusCode(), response);
            } catch (IOException e) {
                if (responseHandler instanceof ClutchAPIDownloadResponseHandler) {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onFailure(e, "");
                } else {
                    responseHandler.onFailure(e, null);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(StatusCodeAndResponse resp) {
            if (responseHandler instanceof ClutchAPIDownloadResponseHandler) {
                if (resp.statusCode == 200) {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onSuccess(resp.response);
                } else {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onFailure(null, resp.response);
                }
            } else {
                if (resp.statusCode == 200) {
                    responseHandler.handleSuccessMessage(resp.response);
                } else {
                    responseHandler.handleFailureMessage(null, resp.response);
                }
            }
        }
    }.execute(request);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpResponse(org.apache.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) StringEntity(org.apache.http.entity.StringEntity) BasicHeader(org.apache.http.message.BasicHeader)

Example 32 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project RoboZombie by sahan.

the class RequestProcessorChain method onInitiate.

/**
	 * <p>Accepts the {@link InvocationContext} given to {@link #run(Object...)}} the {@link RequestProcessorChain} 
	 * and translates the request metadata to a concrete instance of {@link HttpRequestBase}. The 
	 * {@link HttpRequestBase}, together with the {@link InvocationContext} is then given to the root link 
	 * which runs the {@link UriProcessor} and returns the resulting {@link HttpRequestBase}.</p> 
	 * 
	 * <p>See {@link AbstractRequestProcessor}.</p>
	 * 
	 * {@inheritDoc}
	 */
@Override
protected HttpRequestBase onInitiate(ProcessorChainLink<HttpRequestBase, RequestProcessorException> root, Object... args) {
    InvocationContext context = assertAssignable(assertNotEmpty(args)[0], InvocationContext.class);
    HttpRequestBase request = RequestUtils.translateRequestMethod(context);
    //allow any exceptions to elevate to a chain-wide failure
    return root.getProcessor().run(context, request);
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) InvocationContext(com.lonepulse.robozombie.proxy.InvocationContext)

Example 33 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project RoboZombie by sahan.

the class ProxyInvocation method invoke.

/**
	 * <p>Allows the request invocation to progress by directing each stage of the process from context 
	 * instantiation to request processing, onto request execution and finally response handling.</p>
	 *
	 * @return the result of the invocation as specified by the request definition on the endpoint
	 * <br><br>
	 * @throws RoboZombieRuntimeException
	 * 			(or any extension therein) if the request invocation failed on the proxy instance
	 * <br><br>
	 * @since 1.3.0
	 */
@Override
public Object invoke() {
    HttpRequestBase request = template.buildRequest(context);
    HttpResponse response = template.executeRequest(context, request);
    return response == null ? null : template.handleResponse(context, response);
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpResponse(org.apache.http.HttpResponse)

Example 34 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project RoboZombie by sahan.

the class InterceptorEndpointTest method testParamInterceptor.

/**
	 * <p>Test for {@link Interceptor}s passed as a request parameters.</p>
	 * 
	 * @since 1.3.0
	 */
@Test
public final void testParamInterceptor() {
    Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
    String subpath = "/param";
    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200)));
    final String value = "param";
    interceptorEndpoint.paramInterceptor(new Interceptor() {

        public void intercept(InvocationContext context, HttpRequestBase request) {
            request.addHeader("X-Header", value);
        }
    });
    verify(getRequestedFor(urlEqualTo(subpath)).withHeader("X-Header", equalTo("endpoint")).withHeader("X-Header", equalTo("request")).withHeader("X-Header", equalTo(value)).withHeader("Accept-Charset", equalTo("utf-8")));
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) InvocationContext(com.lonepulse.robozombie.proxy.InvocationContext) Interceptor(com.lonepulse.robozombie.request.Interceptor) Test(org.junit.Test)

Example 35 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project xUtils by wyouflf.

the class SyncHttpHandler method handleResponse.

private ResponseStream handleResponse(HttpResponse response) throws HttpException, IOException {
    if (response == null) {
        throw new HttpException("response is null");
    }
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    if (statusCode < 300) {
        ResponseStream responseStream = new ResponseStream(response, charset, requestUrl, expiry);
        responseStream.setRequestMethod(requestMethod);
        return responseStream;
    } else if (statusCode == 301 || statusCode == 302) {
        if (httpRedirectHandler == null) {
            httpRedirectHandler = new DefaultHttpRedirectHandler();
        }
        HttpRequestBase request = httpRedirectHandler.getDirectRequest(response);
        if (request != null) {
            return this.sendRequest(request);
        }
    } else if (statusCode == 416) {
        throw new HttpException(statusCode, "maybe the file has downloaded completely");
    } else {
        throw new HttpException(statusCode, status.getReasonPhrase());
    }
    return null;
}
Also used : StatusLine(org.apache.http.StatusLine) DefaultHttpRedirectHandler(com.lidroid.xutils.http.callback.DefaultHttpRedirectHandler) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpException(com.lidroid.xutils.exception.HttpException)

Aggregations

HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)63 HttpResponse (org.apache.http.HttpResponse)28 HttpGet (org.apache.http.client.methods.HttpGet)20 IOException (java.io.IOException)18 Header (org.apache.http.Header)13 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 HttpPost (org.apache.http.client.methods.HttpPost)13 HttpEntity (org.apache.http.HttpEntity)10 StringEntity (org.apache.http.entity.StringEntity)10 URI (java.net.URI)9 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)9 Test (org.junit.Test)9 InputStream (java.io.InputStream)7 URISyntaxException (java.net.URISyntaxException)7 ArrayList (java.util.ArrayList)7 HttpHead (org.apache.http.client.methods.HttpHead)7 HttpPut (org.apache.http.client.methods.HttpPut)6 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)5 HttpEntityEnclosingRequestBase (org.apache.http.client.methods.HttpEntityEnclosingRequestBase)5 HashMap (java.util.HashMap)4