Search in sources :

Example 71 with HttpResponse

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

the class FileUtil method postFile.

/**
     * Uploads a file via a POST request to a URL.
     * @param fileLocation  path to the file that will be uploaded
     * @param title         title of the video
     * @param slug          slug of the video 
     * @param description   description of the video
     * @param video_type    format of the video (mp4, mpg, avi, etc.)
     * @param checksum      checksum of the file that will be uploaded
     * @param is_public     publicity settings of the file
     * @param pbUpload      progress bar for the upload
     * @param fileSize      the length, in bytes, of the file to be uploaded
     * @param csrf_token    csrf token for the POST request
     * @param user_id       Screenbird user id of the uploader
     * @param channel_id    Screenbird channel id to where the video will be uploaded to
     * @param an_tok        anonymous token identifier if the uploader is not logged in to Screenbird
     * @param listener      listener for the upload
     * @param upload_url    URL where the POST request will be sent to.
     * @return
     * @throws IOException 
     */
public static String[] postFile(String fileLocation, String title, String slug, String description, String video_type, String checksum, Boolean is_public, final JProgressBar pbUpload, long fileSize, String csrf_token, String user_id, String channel_id, String an_tok, 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);
    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 cbChannel_id = new StringBody(channel_id);
    mpEntity.addPart("channel_id", cbChannel_id);
    ContentBody cbAnonym_id = new StringBody(an_tok);
    mpEntity.addPart("an_tok", 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);
    log("===================================================");
    log("executing request " + httppost.getRequestLine());
    log("===================================================");
    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;
    log("===================================================");
    log("response " + response.toString());
    log("===================================================");
    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) FileBody(org.apache.http.entity.mime.content.FileBody) 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.screencap.components.progressbar.ProgressMultiPartEntity) HttpResponse(org.apache.http.HttpResponse) File(java.io.File) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 72 with HttpResponse

use of org.apache.http.HttpResponse in project ats-framework by Axway.

the class HttpClient method processHttpRequest.

/**
     * Perform prepared request and optionally return the response
     * @param httpRequest HttpGet, HttpPost etc
     * @param needResponse do we need the response, if false - then null is returned
     * @return the response from the request as an {@link InputStream} or a {@link String} object
     * @throws FileTransferException
     */
private Object processHttpRequest(HttpUriRequest httpRequest, boolean needResponse, boolean returnAsString) throws FileTransferException {
    HttpEntity responseEntity = null;
    boolean responseNotConsumed = true;
    OutputStream outstream = null;
    String errMsg = "Unable to complete request!";
    String responseAsString = null;
    InputStream responseAsStream = null;
    try {
        // send request
        HttpResponse response = httpClient.execute(httpRequest, httpContext);
        if (200 != response.getStatusLine().getStatusCode()) {
            throw new FileTransferException("Request to '" + httpRequest.getURI() + "' returned " + response.getStatusLine());
        }
        // get the response
        responseEntity = response.getEntity();
        if (!needResponse) {
            responseNotConsumed = true;
        } else {
            if (responseEntity != null) {
                if (!returnAsString) {
                    responseAsStream = responseEntity.getContent();
                } else {
                    int respLengthEstimate = (int) responseEntity.getContentLength();
                    if (respLengthEstimate < 0) {
                        respLengthEstimate = 1024;
                    }
                    outstream = new ByteArrayOutputStream(respLengthEstimate);
                    responseEntity.writeTo(outstream);
                    outstream.flush();
                    responseAsString = outstream.toString();
                }
                responseNotConsumed = false;
            }
        }
    } catch (ClientProtocolException e) {
        log.error(errMsg, e);
        throw new FileTransferException(e);
    } catch (IOException e) {
        log.error(errMsg, e);
        throw new FileTransferException(e);
    } finally {
        if (responseEntity != null && outstream != null) {
            IoUtils.closeStream(outstream);
        }
        if (responseNotConsumed) {
            try {
                // We were not able to properly stream the entity content to the local file system.
                // The next line consumes the entity content closes the underlying stream.
                EntityUtils.consume(responseEntity);
            } catch (IOException e) {
            // we tried our best to release the resources
            }
        }
    }
    log.info("Successfully completed GET request '" + httpRequest.getURI() + "'");
    if (returnAsString) {
        return responseAsString;
    }
    return responseAsStream;
}
Also used : FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) HttpResponse(org.apache.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 73 with HttpResponse

use of org.apache.http.HttpResponse in project ats-framework by Axway.

the class HttpClient method performUploadFile.

@Override
protected void performUploadFile(String localFile, String remoteDir, String remoteFile) throws FileTransferException {
    checkClientInitialized();
    final String uploadUrl = constructUploadUrl(remoteDir, remoteFile);
    log.info("Uploading " + uploadUrl);
    HttpEntityEnclosingRequestBase uploadMethod;
    Object uploadMethodObject = customProperties.get(HTTP_HTTPS_UPLOAD_METHOD);
    if (uploadMethodObject == null || !uploadMethodObject.toString().equals(HTTP_HTTPS_UPLOAD_METHOD__POST)) {
        uploadMethod = new HttpPut(uploadUrl);
    } else {
        uploadMethod = new HttpPost(uploadUrl);
    }
    String contentType = DEFAULT_HTTP_HTTPS_UPLOAD_CONTENT_TYPE;
    Object contentTypeObject = customProperties.get(HTTP_HTTPS_UPLOAD_CONTENT_TYPE);
    if (contentTypeObject != null) {
        contentType = contentTypeObject.toString();
    }
    FileEntity fileUploadEntity = new FileEntity(new File(localFile), ContentType.parse(contentType));
    uploadMethod.setEntity(fileUploadEntity);
    HttpResponse response = null;
    try {
        // add headers specified by the user
        addRequestHeaders(uploadMethod);
        // upload the file
        response = httpClient.execute(uploadMethod, httpContext);
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode < 200 || responseCode > 206) {
            // 204 No Content - there was a file with same name on same location, we replaced it
            throw new FileTransferException("Uploading '" + uploadUrl + "' returned '" + response.getStatusLine() + "'");
        }
    } catch (ClientProtocolException e) {
        log.error("Unable to upload file!", e);
        throw new FileTransferException(e);
    } catch (IOException e) {
        log.error("Unable to upload file!", e);
        throw new FileTransferException(e);
    } finally {
        // the UPLOAD returns response body on error
        if (response != null && response.getEntity() != null) {
            HttpEntity responseEntity = response.getEntity();
            // the underlying stream has been closed
            try {
                EntityUtils.consume(responseEntity);
            } catch (IOException e) {
            // we tried our best to release the resources
            }
        }
    }
    log.info("Successfully uploaded '" + localFile + "' to '" + remoteDir + remoteFile + "', host " + this.hostname);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) FileEntity(org.apache.http.entity.FileEntity) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpPut(org.apache.http.client.methods.HttpPut) ClientProtocolException(org.apache.http.client.ClientProtocolException) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) File(java.io.File)

Example 74 with HttpResponse

use of org.apache.http.HttpResponse in project android-player-samples by BrightcoveOS.

the class MainActivity method httpGet.

public String httpGet(String url) {
    String domain = getResources().getString(R.string.ais_domain);
    String result = "";
    CookieStore cookieStore = new BasicCookieStore();
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    // If we have a cookie stored, parse and use it. Otherwise, use a default http client.
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        if (!authorizationCookie.equals("")) {
            String[] cookies = authorizationCookie.split(";");
            for (int i = 0; i < cookies.length; i++) {
                String[] kvp = cookies[i].split("=");
                if (kvp.length != 2) {
                    throw new Exception("Illegal cookie: missing key/value pair.");
                }
                BasicClientCookie c = new BasicClientCookie(kvp[0], kvp[1]);
                c.setDomain(domain);
                cookieStore.addCookie(c);
            }
        }
        HttpResponse httpResponse = httpClient.execute(httpGet, localContext);
        result = EntityUtils.toString(httpResponse.getEntity());
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage());
    }
    return result;
}
Also used : CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 75 with HttpResponse

use of org.apache.http.HttpResponse in project Activiti by Activiti.

the class BaseJPARestTestCase method assertResultsPresentInPostDataResponseWithStatusCheck.

protected void assertResultsPresentInPostDataResponseWithStatusCheck(String url, ObjectNode body, int expectedStatusCode, String... expectedResourceIds) throws JsonProcessingException, IOException {
    int numberOfResultsExpected = 0;
    if (expectedResourceIds != null) {
        numberOfResultsExpected = expectedResourceIds.length;
    }
    // Do the actual call
    HttpPost post = new HttpPost(SERVER_URL_PREFIX + url);
    post.setEntity(new StringEntity(body.toString()));
    HttpResponse response = executeHttpRequest(post, expectedStatusCode);
    if (expectedStatusCode == HttpStatus.SC_OK) {
        // Check status and size
        JsonNode rootNode = objectMapper.readTree(response.getEntity().getContent());
        JsonNode dataNode = rootNode.get("data");
        assertEquals(numberOfResultsExpected, dataNode.size());
        // Check presence of ID's
        if (expectedResourceIds != null) {
            List<String> toBeFound = new ArrayList<String>(Arrays.asList(expectedResourceIds));
            Iterator<JsonNode> it = dataNode.iterator();
            while (it.hasNext()) {
                String id = it.next().get("id").textValue();
                toBeFound.remove(id);
            }
            assertTrue("Not all entries have been found in result, missing: " + StringUtils.join(toBeFound, ", "), toBeFound.isEmpty());
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Aggregations

HttpResponse (org.apache.http.HttpResponse)4168 Test (org.junit.Test)2110 HttpGet (org.apache.http.client.methods.HttpGet)1770 IOException (java.io.IOException)1000 URI (java.net.URI)817 HttpPost (org.apache.http.client.methods.HttpPost)699 HttpClient (org.apache.http.client.HttpClient)550 HttpEntity (org.apache.http.HttpEntity)496 TestHttpClient (io.undertow.testutils.TestHttpClient)403 InputStream (java.io.InputStream)373 Header (org.apache.http.Header)370 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)333 StringEntity (org.apache.http.entity.StringEntity)332 HttpPut (org.apache.http.client.methods.HttpPut)310 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)307 ArrayList (java.util.ArrayList)296 Identity (org.olat.core.id.Identity)262 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)237 File (java.io.File)192 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)191