Example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity

List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity

Introduction

In this page you can find the example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity.

Prototype

public MultipartEntity() 

Source Link

Usage

From source file:com.marketplace.io.Sender.java

/**
 * Perform a complex HTTP Put (send files over the network)
 * //from   w  w w.  ja  v  a 2  s .co  m
 * @param data
 *            file that needs to be sent
 * @param mimeType
 *            the content type of file
 * @param filename
 *            the name of file
 * @param url
 *            the location to send the file to
 * @throws ConnectivityException
 *             thrown if there was a problem connecting with the database
 */
public void doComplexHttpPut(byte[] data, String mimeType, String filename, String url)
        throws ConnectivityException {
    HttpResponse httpResponse = null;

    try {
        httpPut = new HttpPut();
        httpPut.setURI(new URI(url));
        httpPut.addHeader("content_type", "image/jpeg");
    } catch (URISyntaxException e) {
        throw new ConnectivityException("Error occured while setting URL");
    }

    ContentBody contentBody = new ByteArrayBody(data, mimeType, filename);

    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("image", contentBody);

    httpPut.setEntity(multipartEntity);

    try {
        httpResponse = httpClient.execute(httpPut);
        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            entity.getContent().close();
        }

    } catch (ClientProtocolException e) {
        throw new ConnectivityException("Error occured in Client Protocol");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:bluej.collect.DataCollectorImpl.java

public static void debuggerStepOver(Project project, String threadName, SourceLocation[] stack) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[thread_name]", CollectUtility.toBody(threadName));
    submitDebuggerEventWithLocation(project, EventName.DEBUGGER_STEP_OVER, mpe, stack);
}

From source file:org.fcrepo.test.api.TestAdminAPI.java

private HttpResponse putOrPost(String method, Object requestContent, boolean authenticate) throws Exception {

    if (url == null || url.length() == 0) {
        throw new IllegalArgumentException("url must be a non-empty value");
    } else if (!(url.startsWith("http://") || url.startsWith("https://"))) {
        url = getBaseURL() + url;/*www.j  ava 2 s .co m*/
    }

    HttpEntityEnclosingRequestBase httpMethod = null;
    try {
        if (method.equals("PUT")) {
            httpMethod = new HttpPut(url);
        } else if (method.equals("POST")) {
            httpMethod = new HttpPost(url);
        } else {
            throw new IllegalArgumentException("method must be one of PUT or POST.");
        }
        httpMethod.setHeader(HttpHeaders.CONNECTION, "Keep-Alive");
        if (requestContent != null) {
            if (requestContent instanceof String) {
                StringEntity entity = new StringEntity((String) requestContent, Charset.forName("UTF-8"));
                entity.setChunked(chunked);
                httpMethod.setEntity(entity);
            } else if (requestContent instanceof File) {
                MultipartEntity entity = new MultipartEntity();
                entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
                entity.addPart("param_name", new StringBody("value"));
                httpMethod.setEntity(entity);
            } else {
                throw new IllegalArgumentException("requestContent must be a String or File");
            }
        }
        return getClient(authenticate).execute(httpMethod);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:bluej.collect.DataCollectorImpl.java

public static void debuggerHitBreakpoint(Project project, String threadName, SourceLocation[] stack) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[thread_name]", CollectUtility.toBody(threadName));
    submitDebuggerEventWithLocation(project, EventName.DEBUGGER_HIT_BREAKPOINT, mpe, stack);
}

From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java

@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type Other And"
        + " Source File through the publisher rest API ", dependsOnMethods = "testAddDocumentToAnAPISupportToFile")
public void testAddDocumentToAnAPIOtherFile() throws Exception {

    String fileNameAPIM629 = "APIM629.txt";
    String docName = "APIM629PublisherTestHowTo-File-summary";
    String docType = "Other";
    String sourceType = "file";
    String newType = "Type APIM629";
    String summary = "Testing";
    String mimeType = "text/plain";
    String docUrl = "http://";
    String filePathAPIM629 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts"
            + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM629;
    String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag";

    //Send Http Post request to add a new file
    HttpPost httppost = new HttpPost(addDocUrl);
    File file = new File(filePathAPIM629);
    FileBody fileBody = new FileBody(file, "text/plain");

    //Create multipart entity to upload file as multipart file
    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("docLocation", fileBody);
    multipartEntity.addPart("mode", new StringBody(""));
    multipartEntity.addPart("docName", new StringBody(docName));
    multipartEntity.addPart("docUrl", new StringBody(docUrl));
    multipartEntity.addPart("sourceType", new StringBody(sourceType));
    multipartEntity.addPart("summary", new StringBody(summary));
    multipartEntity.addPart("docType", new StringBody(docType));
    multipartEntity.addPart("version", new StringBody(apiVersion));
    multipartEntity.addPart("apiName", new StringBody(apiName));
    multipartEntity.addPart("action", new StringBody("addDocumentation"));
    multipartEntity.addPart("provider", new StringBody(apiProvider));
    multipartEntity.addPart("mimeType", new StringBody(mimeType));
    multipartEntity.addPart("newType", new StringBody(newType));
    multipartEntity.addPart("optionsRadios", new StringBody(docType));
    multipartEntity.addPart("optionsRadios1", new StringBody(sourceType));
    multipartEntity.addPart("optionsRadios1", new StringBody(sourceType));

    httppost.setEntity(multipartEntity);

    //Upload created file and validate
    HttpResponse response = httpClient.execute(httppost);
    HttpEntity entity = response.getEntity();
    JSONObject jsonObject1 = new JSONObject(EntityUtils.toString(entity));
    assertFalse(jsonObject1.getBoolean("error"), "Error when adding files to the API ");
}

From source file:bluej.collect.DataCollectorImpl.java

public static void codePadSuccess(Package pkg, String command, String output) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[codepad][outcome]", CollectUtility.toBody("success"));
    mpe.addPart("event[codepad][command]", CollectUtility.toBody(command));
    mpe.addPart("event[codepad][result]", CollectUtility.toBody(output));
    submitEvent(pkg.getProject(), pkg, EventName.CODEPAD, new PlainEvent(mpe));
}

From source file:org.craftercms.social.UCGRestServicesTest.java

public static void main(String[] args) throws Exception {

    ProfileClient profileRestClient = new ProfileRestClientImpl();

    String token = profileRestClient.getAppToken("craftersocial", "craftersocial");
    Tenant tenant = profileRestClient.getTenantByName(token, "testing");
    String ticket = profileRestClient.getTicket(token, "admin", "admin", tenant.getId());
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    qparams.add(new BasicNameValuePair("target", "testing"));

    qparams.add(new BasicNameValuePair("textContent", "Content"));

    URI uri = URIUtils.createURI("http", "localhost", 8080, "crafter-social/api/1/ugc/" + "create.json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uri);
    File file = new File(
            "/Users/alvarogonzalez/development/projects/crafter-social/rest/src/test/resources/test.txt");
    MultipartEntity me = new MultipartEntity();

    //The usual form parameters can be added this way
    //me.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
    //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;

    /*Need to construct a FileBody with the file that needs to be attached and specify the mime type of the file. Add the fileBody to the request as an another part.
    This part will be considered as file part and the rest of them as usual form-data parts*/
    FileBody fileBody = new FileBody(file, "application/octect-stream");
    //me.addPart("ticket", new StringBody(token)) ;
    //me.addPart("target", new StringBody("my-test")) ;
    me.addPart("attachments", fileBody);

    httppost.setEntity(me);//from w w  w . ja  va  2 s . c o m
    httpclient.execute(httppost);

}

From source file:bluej.collect.DataCollectorImpl.java

public static void codePadError(Package pkg, String command, String error) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[codepad][outcome]", CollectUtility.toBody("error"));
    mpe.addPart("event[codepad][command]", CollectUtility.toBody(command));
    mpe.addPart("event[codepad][error]", CollectUtility.toBody(error));
    submitEvent(pkg.getProject(), pkg, EventName.CODEPAD, new PlainEvent(mpe));
}

From source file:com.marketplace.io.Sender.java

/**
 * Perform a complex HTTP Post (send files over the network)
 * /*from w  w w. j  a v  a2 s.c o  m*/
 * @param data
 *            file that needs to be sent
 * @param mimeType
 *            the content type of file
 * @param filename
 *            the name of file
 * @param url
 *            the location to send the file to
 * @throws ConnectivityException
 *             thrown if there was a problem connecting with the database
 */
public void doComplexHttpPost(byte[] data, String mimeType, String filename, String url)
        throws ConnectivityException {
    HttpResponse httpResponse = null;

    try {
        httpPost = new HttpPost();
        httpPost.setURI(new URI(url));
        httpPost.addHeader("content_type", "image/jpeg");
    } catch (URISyntaxException e) {
        throw new ConnectivityException("Error occured while setting URL");
    }

    ContentBody contentBody = new ByteArrayBody(data, mimeType, filename);

    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("image", contentBody);

    httpPost.setEntity(multipartEntity);

    try {
        httpResponse = httpClient.execute(httpPost);
        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            entity.getContent().close();
        }

    } catch (ClientProtocolException e) {
        throw new ConnectivityException("Error occured in Client Protocol");
    } catch (IOException e) {
        e.printStackTrace();
    }
}