Search in sources :

Example 26 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project infoarchive-sip-sdk by Enterprise-Content-Management.

the class ApacheHttpClient method post.

@Override
public <T> T post(String uri, Collection<Header> headers, Class<T> type, Part... parts) throws IOException {
    HttpPost request = newPost(uri, headers);
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    for (Part part : parts) {
        entityBuilder.addPart(part.getName(), newContentBody(part));
    }
    request.setEntity(entityBuilder.build());
    return execute(request, type);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) TextPart(com.opentext.ia.sdk.support.http.TextPart) BinaryPart(com.opentext.ia.sdk.support.http.BinaryPart) Part(com.opentext.ia.sdk.support.http.Part)

Example 27 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project undertow by undertow-io.

the class ServletCertAndDigestAuthTestCase method testMultipartRequest.

@Test
public void testMultipartRequest() throws Exception {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 2000; i++) {
        sb.append("0123456789");
    }
    try (TestHttpClient client = new TestHttpClient()) {
        // create POST request
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart("part1", new ByteArrayBody(sb.toString().getBytes(), "file.txt"));
        builder.addPart("part2", new StringBody("0123456789", ContentType.TEXT_HTML));
        HttpEntity entity = builder.build();
        client.setSSLContext(clientSSLContext);
        String url = DefaultServer.getDefaultServerSSLAddress() + BASE_PATH + "multipart";
        HttpPost post = new HttpPost(url);
        post.setEntity(entity);
        post.addHeader(AUTHORIZATION.toString(), BASIC + " " + FlexBase64.encodeString(("user1" + ":" + "password1").getBytes(StandardCharsets.UTF_8), false));
        HttpResponse result = client.execute(post);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) ByteArrayBody(org.apache.http.entity.mime.content.ByteArrayBody) HttpResponse(org.apache.http.HttpResponse) SecurityConstraint(io.undertow.servlet.api.SecurityConstraint) TestHttpClient(io.undertow.testutils.TestHttpClient) Test(org.junit.Test)

Example 28 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project google-cloud-java by GoogleCloudPlatform.

the class ITStorageSnippets method testGenerateSignedPostPolicyV4.

@Test
public void testGenerateSignedPostPolicyV4() throws Exception {
    PrintStream systemOut = System.out;
    final ByteArrayOutputStream snippetOutputCapture = new ByteArrayOutputStream();
    System.setOut(new PrintStream(snippetOutputCapture));
    GenerateSignedPostPolicyV4.generateSignedPostPolicyV4(PROJECT_ID, BUCKET, "my-object");
    String snippetOutput = snippetOutputCapture.toString();
    System.setOut(systemOut);
    assertTrue(snippetOutput.contains("<form action='https://storage.googleapis.com/" + BUCKET + "/'"));
    assertTrue(snippetOutput.contains("<input name='key' value='my-object'"));
    assertTrue(snippetOutput.contains("<input name='x-goog-signature'"));
    assertTrue(snippetOutput.contains("<input name='x-goog-date'"));
    assertTrue(snippetOutput.contains("<input name='x-goog-credential'"));
    assertTrue(snippetOutput.contains("<input name='x-goog-algorithm' value='GOOG4-RSA-SHA256'"));
    assertTrue(snippetOutput.contains("<input name='policy'"));
    assertTrue(snippetOutput.contains("<input name='x-goog-meta-test' value='data'"));
    assertTrue(snippetOutput.contains("<input type='file' name='file'/>"));
    String[] output = snippetOutput.split("'");
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost request = new HttpPost(output[1]);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    Map<String, String> policy = new HashMap<>();
    /**
     * When splitting by "'", any element in the form has its value two array elements ahead of it,
     * for example ["x-goog-algorithm", "value=", "GOOG4-RSA-SHA256"] We take advantage of this to
     * make a map which has any policy element easily accessible. The map also has a lot of noise,
     * but we just use the parts we need
     */
    for (int i = 3; i < output.length - 3; i += 2) {
        policy.put(output[i], output[i + 2]);
    }
    builder.addTextBody("x-goog-date", policy.get("x-goog-date"));
    builder.addTextBody("x-goog-meta-test", "data");
    builder.addTextBody("x-goog-algorithm", "GOOG4-RSA-SHA256");
    builder.addTextBody("x-goog-credential", policy.get("x-goog-credential"));
    builder.addTextBody("key", "my-object");
    builder.addTextBody("x-goog-signature", policy.get("x-goog-signature"));
    builder.addTextBody("policy", policy.get("policy"));
    File file = File.createTempFile("temp", "file");
    Files.write(file.toPath(), "hello world".getBytes());
    builder.addBinaryBody("file", new FileInputStream(file), ContentType.APPLICATION_OCTET_STREAM, file.getName());
    request.setEntity(builder.build());
    client.execute(request);
    assertEquals("hello world", new String(storage.get(BUCKET, "my-object").getContent()));
}
Also used : PrintStream(java.io.PrintStream) HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HashMap(java.util.HashMap) HttpClient(org.apache.http.client.HttpClient) ByteArrayOutputStream(java.io.ByteArrayOutputStream) File(java.io.File) FileInputStream(java.io.FileInputStream) Test(org.junit.Test)

Example 29 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project zm-mailbox by Zimbra.

the class ZMailbox method uploadAttachments.

/* ------------------------------------------------- */
/**
 * Uploads files to <tt>FileUploadServlet</tt>.
 * @return the attachment id
 */
public String uploadAttachments(File[] files, int msTimeout) throws ServiceException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        String contentType = URLConnection.getFileNameMap().getContentTypeFor(file.getName());
        if (contentType != null) {
            builder.addBinaryBody("upfile", file, ContentType.create(contentType, "UTF-8"), file.getName());
        } else {
            builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, file.getName());
        }
    }
    return uploadAttachments(builder, msTimeout);
}
Also used : MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) File(java.io.File)

Example 30 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project zm-mailbox by Zimbra.

the class LmcSendMsgRequest method postAttachment.

/*
    * Post the attachment represented by File f and return the attachment ID
    */
public String postAttachment(String uploadURL, LmcSession session, File f, // cookie domain e.g. ".example.zimbra.com"
String domain, int msTimeout) throws LmcSoapClientException, IOException, HttpException {
    String aid = null;
    // set the cookie.
    if (session == null)
        System.err.println(System.currentTimeMillis() + " " + Thread.currentThread() + " LmcSendMsgRequest.postAttachment session=null");
    HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpPost post = new HttpPost(uploadURL);
    ZAuthToken zat = session.getAuthToken();
    Map<String, String> cookieMap = zat.cookieMap(false);
    if (cookieMap != null) {
        BasicCookieStore initialState = new BasicCookieStore();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            BasicClientCookie cookie = new BasicClientCookie(ck.getKey(), ck.getValue());
            cookie.setDomain(domain);
            cookie.setPath("/");
            cookie.setSecure(false);
            cookie.setExpiryDate(null);
            initialState.addCookie(cookie);
        }
        clientBuilder.setDefaultCookieStore(initialState);
        RequestConfig reqConfig = RequestConfig.copy(ZimbraHttpConnectionManager.getInternalHttpConnMgr().getZimbraConnMgrParams().getReqConfig()).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
        clientBuilder.setDefaultRequestConfig(reqConfig);
    }
    SocketConfig config = SocketConfig.custom().setSoTimeout(msTimeout).build();
    clientBuilder.setDefaultSocketConfig(config);
    int statusCode = -1;
    try {
        String contentType = URLConnection.getFileNameMap().getContentTypeFor(f.getName());
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("upfile", f, ContentType.create(contentType, "UTF-8"), f.getName());
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        HttpClient client = clientBuilder.build();
        HttpResponse httpResponse = HttpClientUtil.executeMethod(client, post);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        // parse the response
        if (statusCode == 200) {
            // paw through the returned HTML and get the attachment id
            String response = EntityUtils.toString(httpResponse.getEntity());
            // System.out.println("response is\n" + response);
            int lastQuote = response.lastIndexOf("'");
            int firstQuote = response.indexOf("','") + 3;
            if (lastQuote == -1 || firstQuote == -1)
                throw new LmcSoapClientException("Attachment post failed, unexpected response: " + response);
            aid = response.substring(firstQuote, lastQuote);
        } else {
            throw new LmcSoapClientException("Attachment post failed, status=" + statusCode);
        }
    } catch (IOException | HttpException e) {
        System.err.println("Attachment post failed");
        e.printStackTrace();
        throw e;
    } finally {
        post.releaseConnection();
    }
    return aid;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) SocketConfig(org.apache.http.config.SocketConfig) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) IOException(java.io.IOException) ZAuthToken(com.zimbra.common.auth.ZAuthToken) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpClient(org.apache.http.client.HttpClient) HttpException(org.apache.http.HttpException) Map(java.util.Map)

Aggregations

MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)227 HttpEntity (org.apache.http.HttpEntity)166 ArrayList (java.util.ArrayList)126 HashMap (java.util.HashMap)123 VolleyError (com.android.volley.VolleyError)120 ApiException (io.swagger.client.ApiException)120 Pair (io.swagger.client.Pair)120 HttpPost (org.apache.http.client.methods.HttpPost)68 ExecutionException (java.util.concurrent.ExecutionException)61 TimeoutException (java.util.concurrent.TimeoutException)61 Response (com.android.volley.Response)60 File (java.io.File)40 List (java.util.List)40 HttpResponse (org.apache.http.HttpResponse)37 IOException (java.io.IOException)31 Test (org.junit.Test)26 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)22 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)22 StringBody (org.apache.http.entity.mime.content.StringBody)18 ApiSafeResultCollectTokenResponse (io.swagger.client.model.ApiSafeResultCollectTokenResponse)16