Search in sources :

Example 21 with HttpEntity

use of org.apache.http.HttpEntity in project jersey by jersey.

the class ApacheConnector method apply.

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);
    try {
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName());
        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null ? Statuses.from(response.getStatusLine().getStatusCode()) : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }
        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }
            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }
        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }
        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) ClientResponse(org.glassfish.jersey.client.ClientResponse) BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) IOException(java.io.IOException) URI(java.net.URI) ProcessingException(javax.ws.rs.ProcessingException) IOException(java.io.IOException) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Header(org.apache.http.Header) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProcessingException(javax.ws.rs.ProcessingException)

Example 22 with HttpEntity

use of org.apache.http.HttpEntity in project jersey by jersey.

the class ApacheConnector method getUriHttpRequest.

private HttpUriRequest getUriHttpRequest(final ClientRequest clientRequest) {
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.copy(requestConfig);
    final int connectTimeout = clientRequest.resolveProperty(ClientProperties.CONNECT_TIMEOUT, -1);
    final int socketTimeout = clientRequest.resolveProperty(ClientProperties.READ_TIMEOUT, -1);
    if (connectTimeout >= 0) {
        requestConfigBuilder.setConnectTimeout(connectTimeout);
    }
    if (socketTimeout >= 0) {
        requestConfigBuilder.setSocketTimeout(socketTimeout);
    }
    final Boolean redirectsEnabled = clientRequest.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, requestConfig.isRedirectsEnabled());
    requestConfigBuilder.setRedirectsEnabled(redirectsEnabled);
    final Boolean bufferingEnabled = clientRequest.resolveProperty(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.class) == RequestEntityProcessing.BUFFERED;
    final HttpEntity entity = getHttpEntity(clientRequest, bufferingEnabled);
    return RequestBuilder.create(clientRequest.getMethod()).setUri(clientRequest.getUri()).setConfig(requestConfigBuilder.build()).setEntity(entity).build();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) RequestEntityProcessing(org.glassfish.jersey.client.RequestEntityProcessing)

Example 23 with HttpEntity

use of org.apache.http.HttpEntity in project screenbird by adamhub.

the class FileUtil method postData.

public static String[] postData(String data, final JProgressBar pbUpload, String anonymous_token, String csrf_token, String user_id, ProgressBarUploadProgressListener listener, String upload_url) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(upload_url);
    //File file = new File(fileLocation);
    //MultipartEntity mpEntity = new MultipartEntity();
    ProgressMultiPartEntity mpEntity = new ProgressMultiPartEntity(listener);
    //ContentBody cbFile = new FileBody(file, "video/quicktime");
    //mpEntity.addPart("videoupload", cbFile);
    //ContentBody cbToken = new StringBody(title);
    //mpEntity.addPart("csrfmiddlewaretoken", cbToken);
    ContentBody cbUser_id = new StringBody(user_id);
    mpEntity.addPart("user_id", cbUser_id);
    ContentBody cbAnonym_id = new StringBody(MediaUtil.getMacAddress());
    mpEntity.addPart("anonym_id", cbAnonym_id);
    //ContentBody cbTitle = new StringBody(title);
    //mpEntity.addPart("title", cbTitle);
    //        ContentBody cbSlug = new StringBody(slug);
    //        mpEntity.addPart("slug", cbSlug);
    //        ContentBody cbPublic = new StringBody(is_public ? "1" : "0");
    //        mpEntity.addPart("is_public", cbPublic);
    //        ContentBody cbDescription = new StringBody(description);
    //        mpEntity.addPart("description", cbDescription);
    //        ContentBody cbChecksum = new StringBody(checksum);
    //        mpEntity.addPart("checksum", cbChecksum);
    //        ContentBody cbType = new StringBody(video_type);
    //        mpEntity.addPart("video_type", cbType);
    httppost.setEntity(mpEntity);
    System.out.println("===================================================");
    System.out.println("executing request " + httppost.getRequestLine());
    System.out.println("===================================================");
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    String[] result = new String[2];
    String status = response.getStatusLine().toString();
    result[0] = (status.indexOf("200") >= 0) ? "200" : status;
    System.out.println("===================================================");
    System.out.println("status from request " + result[0]);
    System.out.println("===================================================");
    if (resEntity != null) {
        result[1] = EntityUtils.toString(resEntity);
        EntityUtils.consume(resEntity);
    }
    httpclient.getConnectionManager().shutdown();
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ContentBody(org.apache.http.entity.mime.content.ContentBody) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) ProgressMultiPartEntity(com.bixly.pastevid.util.view.ProgressMultiPartEntity) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 24 with HttpEntity

use of org.apache.http.HttpEntity in project android_frameworks_base by ParanoidAndroid.

the class FsUtils method getLayoutTestsDirContents.

public static List<String> getLayoutTestsDirContents(String dirRelativePath, boolean recurse, boolean mode) {
    String modeString = (mode ? "folders" : "files");
    URL url = null;
    try {
        url = new URL(SCRIPT_URL + "?path=" + dirRelativePath + "&recurse=" + recurse + "&mode=" + modeString);
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "path=" + dirRelativePath + " recurse=" + recurse + " mode=" + modeString, e);
        return new LinkedList<String>();
    }
    HttpGet httpRequest = new HttpGet(url.toString());
    ResponseHandler<LinkedList<String>> handler = new ResponseHandler<LinkedList<String>>() {

        @Override
        public LinkedList<String> handleResponse(HttpResponse response) throws IOException {
            LinkedList<String> lines = new LinkedList<String>();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return lines;
            }
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return lines;
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    lines.add(line);
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
            return lines;
        }
    };
    try {
        return getHttpClient().execute(httpRequest, handler);
    } catch (IOException e) {
        Log.e(LOG_TAG, "getLayoutTestsDirContents(): HTTP GET failed for URL " + url);
        return null;
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL) LinkedList(java.util.LinkedList) BufferedReader(java.io.BufferedReader)

Example 25 with HttpEntity

use of org.apache.http.HttpEntity in project android_frameworks_base by ParanoidAndroid.

the class AndroidHttpClient method toCurl.

/**
     * Generates a cURL command equivalent to the given request.
     */
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();
    builder.append("curl ");
    // add in the method
    builder.append("-X ");
    builder.append(request.getMethod());
    builder.append(" ");
    for (Header header : request.getAllHeaders()) {
        if (!logAuthToken && (header.getName().equals("Authorization") || header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }
    URI uri = request.getURI();
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }
    builder.append("\"");
    builder.append(uri);
    builder.append("\"");
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                if (isBinaryContent(request)) {
                    String base64 = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
                    builder.insert(0, "echo '" + base64 + "' | base64 -d > /tmp/$$.bin; ");
                    builder.append(" --data-binary @/tmp/$$.bin");
                } else {
                    String entityString = stream.toString();
                    builder.append(" --data-ascii \"").append(entityString).append("\"");
                }
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }
    return builder.toString();
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) Header(org.apache.http.Header) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) HttpEntity(org.apache.http.HttpEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) RequestWrapper(org.apache.http.impl.client.RequestWrapper) ByteArrayOutputStream(java.io.ByteArrayOutputStream) URI(java.net.URI)

Aggregations

HttpEntity (org.apache.http.HttpEntity)1391 HttpResponse (org.apache.http.HttpResponse)509 IOException (java.io.IOException)483 HttpGet (org.apache.http.client.methods.HttpGet)391 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)315 HttpPost (org.apache.http.client.methods.HttpPost)305 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)284 Test (org.junit.Test)259 ArrayList (java.util.ArrayList)248 HashMap (java.util.HashMap)177 MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)164 InputStream (java.io.InputStream)163 URI (java.net.URI)153 StatusLine (org.apache.http.StatusLine)149 StringEntity (org.apache.http.entity.StringEntity)148 Header (org.apache.http.Header)136 HttpClient (org.apache.http.client.HttpClient)127 VolleyError (com.android.volley.VolleyError)120 ApiException (io.swagger.client.ApiException)120 Pair (io.swagger.client.Pair)120