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

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

Introduction

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

Prototype

public void addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

From source file:org.apache.sling.validation.testservices.ValidationServiceTest.java

@Test
public void testInvalidRequestModel1() throws IOException, JSONException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("sling:resourceType", new StringBody("validation/test/resourceType1"));
    entity.addPart("field1", new StringBody("Hello World"));
    entity.addPart(SlingPostConstants.RP_OPERATION, new StringBody("validation"));
    RequestExecutor re = getRequestExecutor().execute(
            getRequestBuilder().buildPostRequest("/validation/testing/fakeFolder1/resource").withEntity(entity))
            .assertStatus(200);/*  www  .  j ava2 s.c o m*/
    String content = re.getContent();
    JSONObject jsonResponse = new JSONObject(content);
    assertFalse(jsonResponse.getBoolean("valid"));
    JSONObject failure = jsonResponse.getJSONArray("failures").getJSONObject(0);
    assertEquals("Property does not match the pattern \"^\\p{Upper}+$\".", failure.get("message"));
    assertEquals("field1", failure.get("location"));
    assertEquals(10, failure.get("severity"));
    failure = jsonResponse.getJSONArray("failures").getJSONObject(1);
    assertEquals("Missing required property with name \"field2\".", failure.get("message"));
    assertEquals("", failure.get("location")); // location is empty as the property is not found (property name is part of the message rather)
    assertEquals(0, failure.get("severity"));
}

From source file:com.willowtreeapps.uploader.testflight.TestFlightUploader.java

public Map upload(UploadRequest ur) throws IOException, org.json.simple.parser.ParseException {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpHost targetHost = new HttpHost(HOST);
    HttpPost httpPost = new HttpPost(POST);
    FileBody fileBody = new FileBody(ur.file);

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("api_token", new StringBody(ur.apiToken));
    entity.addPart("team_token", new StringBody(ur.teamToken));
    entity.addPart("notes", new StringBody(ur.buildNotes));
    entity.addPart("file", fileBody);

    if (ur.dsymFile != null) {
        FileBody dsymFileBody = new FileBody(ur.dsymFile);
        entity.addPart("dsym", dsymFileBody);
    }//from www  .  java 2  s  .c  om

    if (ur.lists.length() > 0) {
        entity.addPart("distribution_lists", new StringBody(ur.lists));
    }

    entity.addPart("notify", new StringBody(ur.notifyTeam ? "True" : "False"));
    entity.addPart("replace", new StringBody(ur.replace ? "True" : "False"));
    httpPost.setEntity(entity);

    return this.send(ur, httpClient, targetHost, httpPost);
}

From source file:net.bither.api.UploadAvatarApi.java

@Override
public HttpEntity getHttpEntity() throws Exception {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartEntity.addPart(FILE_KEY, new FileBody(this.mFile));
    return multipartEntity;
}

From source file:com.puppetlabs.geppetto.forge.client.OAuthModule.java

@Override
public AuthResponse authenticate(HttpClient httpClient) throws IOException {
    HttpPost request = new HttpPost(oauthURL);

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("grant_type", new StringBody("password"));
    entity.addPart("client_id", new StringBody(clientId));
    entity.addPart("client_secret", new StringBody(clientSecret));
    entity.addPart("username", new StringBody(username));
    entity.addPart("password", new StringBody(password));
    request.setEntity(entity);//from   w w  w  .  j a v  a 2s  . co m

    return httpClient.execute(request, new JSonResponseHandler<OAuthResponse>(gson, OAuthResponse.class));
}

From source file:com.devbliss.doctest.httpfactory.PostUploadWithoutRedirectImpl.java

public HttpPost createPostRequest(URI uri, Object payload) throws IOException {
    HttpPost httpPost = new HttpPost(uri);
    HttpParams params = new BasicHttpParams();
    params.setParameter(HttpConstants.HANDLE_REDIRECTS, false);
    httpPost.setParams(params);/*from   www. j  a  va 2 s.co  m*/

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart(paramName, fileBodyToUpload);
    httpPost.setEntity(entity);

    return httpPost;
}

From source file:org.codegist.crest.HttpClientRestService.java

private static HttpUriRequest toHttpUriRequest(HttpRequest request) throws UnsupportedEncodingException {
    HttpUriRequest uriRequest;//ww  w  .j a v  a 2s  . c o  m

    String queryString = "";
    if (request.getQueryParams() != null) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : request.getQueryParams().entrySet()) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String qs = URLEncodedUtils.format(params, request.getEncoding());
        queryString = Strings.isNotBlank(qs) ? ("?" + qs) : "";
    }
    String uri = request.getUri().toString() + queryString;

    switch (request.getMeth()) {
    default:
    case GET:
        uriRequest = new HttpGet(uri);
        break;
    case POST:
        uriRequest = new HttpPost(uri);
        break;
    case PUT:
        uriRequest = new HttpPut(uri);
        break;
    case DELETE:
        uriRequest = new HttpDelete(uri);
        break;
    case HEAD:
        uriRequest = new HttpHead(uri);
        break;
    }
    if (uriRequest instanceof HttpEntityEnclosingRequestBase) {
        HttpEntityEnclosingRequestBase enclosingRequestBase = ((HttpEntityEnclosingRequestBase) uriRequest);
        HttpEntity entity;
        if (Params.isForUpload(request.getBodyParams().values())) {
            MultipartEntity multipartEntity = new MultipartEntity();
            for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) {
                ContentBody body;
                if (param.getValue() instanceof InputStream) {
                    body = new InputStreamBody((InputStream) param.getValue(), param.getKey());
                } else if (param.getValue() instanceof File) {
                    body = new FileBody((File) param.getValue());
                } else if (param.getValue() != null) {
                    body = new StringBody(param.getValue().toString(), request.getEncodingAsCharset());
                } else {
                    body = new StringBody(null);
                }
                multipartEntity.addPart(param.getKey(), body);
            }
            entity = multipartEntity;
        } else {
            List<NameValuePair> params = new ArrayList<NameValuePair>(request.getBodyParams().size());
            for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) {
                params.add(new BasicNameValuePair(param.getKey(),
                        param.getValue() != null ? param.getValue().toString() : null));
            }
            entity = new UrlEncodedFormEntity(params, request.getEncoding());
        }

        enclosingRequestBase.setEntity(entity);
    }

    if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
        for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
            uriRequest.setHeader(header.getKey(), header.getValue());
        }
    }

    if (request.getConnectionTimeout() != null && request.getConnectionTimeout() >= 0) {
        HttpConnectionParams.setConnectionTimeout(uriRequest.getParams(),
                request.getConnectionTimeout().intValue());
    }

    if (request.getSocketTimeout() != null && request.getSocketTimeout() >= 0) {
        HttpConnectionParams.setSoTimeout(uriRequest.getParams(), request.getSocketTimeout().intValue());
    }

    return uriRequest;
}

From source file:org.opencastproject.remotetest.server.MultiPartTest.java

@Test
public void testMultiPartPost() throws Exception {

    String mp = "<oc:mediapackage xmlns:oc=\"http://mediapackage.opencastproject.org\" id=\"10.0000/1\" start=\"2007-12-05T13:40:00\" duration=\"1004400000\"></oc:mediapackage>";

    InputStream is = null;//from   www.j a v  a 2 s.  c om
    try {
        is = getClass().getResourceAsStream("/av.mov");
        InputStreamBody fileContent = new InputStreamBody(is, "av.mov");
        MultipartEntity mpEntity = new MultipartEntity();
        mpEntity.addPart("mediaPackage", new StringBody(mp));
        mpEntity.addPart("flavor", new StringBody("presentation/source"));
        mpEntity.addPart("userfile", fileContent);
        HttpPost httppost = new HttpPost(BASE_URL + "/ingest/addAttachment");
        httppost.setEntity(mpEntity);
        HttpResponse response = httpClient.execute(httppost);
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.cli.cmd.LoginWithCredentialsCommand.java

@Override
protected String login(ApplicationContext currentContext) throws CLIException {
    File credentials = new File(pathname);
    if (!credentials.exists()) {
        throw new CLIException(REASON_INVALID_ARGUMENTS,
                String.format("File does not exist: %s", credentials.getAbsolutePath()));
    }/*from   www.j av  a2 s .co  m*/
    if (warn) {
        writeLine(currentContext, "Using the default credentials file: %s", credentials.getAbsolutePath());
    }
    HttpPost request = new HttpPost(currentContext.getResourceUrl("login"));
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("credential",
            new ByteArrayBody(FileUtility.byteArray(credentials), APPLICATION_OCTET_STREAM.getMimeType()));
    request.setEntity(entity);
    HttpResponseWrapper response = execute(request, currentContext);
    if (statusCode(OK) == statusCode(response)) {
        return StringUtility.responseAsString(response).trim();
    } else {
        handleError("An error occurred while logging: ", response, currentContext);
        throw new CLIException(REASON_OTHER, "An error occurred while logging.");
    }
}

From source file:com.gorillalogic.monkeytalk.server.tests.MultipartTest.java

@Test
public void testMultipart() throws IOException, JSONException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/");

    File image = new File("resources/test/base.png");
    FileBody imagePart = new FileBody(image);
    StringBody messagePart = new StringBody("some message");

    MultipartEntity req = new MultipartEntity();
    req.addPart("image", imagePart);
    req.addPart("message", messagePart);
    httppost.setEntity(req);// w  ww .j a v  a2  s. c o  m

    ImageEchoServer server = new ImageEchoServer(PORT);
    HttpResponse response = httpclient.execute(httppost);
    server.stop();

    HttpEntity resp = response.getEntity();
    assertThat(resp.getContentType().getValue(), is("application/json"));

    // sweet one-liner to convert an inputstream to a string from stackoverflow:
    // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string
    String out = new Scanner(resp.getContent()).useDelimiter("\\A").next();

    JSONObject json = new JSONObject(out);

    String base64 = Base64.encodeFromFile("resources/test/base.png");

    assertThat(json.getString("screenshot"), is(base64));
    assertThat(json.getBoolean("imageEcho"), is(true));
}

From source file:uf.edu.uploadTraces.java

boolean sendFile(String Filename) {
    boolean success = false;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(con.getResources().getString((R.string.uploadURL)));

    FileBody bin = new FileBody(new File(Filename));
    try {//from   ww  w .j a va 2s .  c  o m

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("filename", bin);
        //reqEntity.addPart("comment", comment);
        httppost.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        Log.i("iTrust", resEntity.toString());
        success = true;

        //save the last upload time
        pres = con.getSharedPreferences("iTrust", 0);
        SharedPreferences.Editor ed = pres.edit();
        ed.putLong("LastUploadTime", System.currentTimeMillis() / 1000);
        ed.commit();

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return success;

}