Search in sources :

Example 11 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project sling by apache.

the class OsgiConsoleClient method installBundle.

/**
     * Install a bundle using the Felix webconsole HTTP interface, with a specific start level
     * @param f bundle file
     * @param startBundle whether to start or just install the bundle
     * @param startLevel start level
     * @return the sling response
     * @throws ClientException if the request failed
     */
public SlingHttpResponse installBundle(File f, boolean startBundle, int startLevel) throws ClientException {
    // Setup request for Felix Webconsole bundle install
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().addTextBody("action", "install").addBinaryBody("bundlefile", f);
    if (startBundle) {
        builder.addTextBody("bundlestart", "true");
    }
    if (startLevel > 0) {
        builder.addTextBody("bundlestartlevel", String.valueOf(startLevel));
        LOG.info("Installing bundle {} at start level {}", f.getName(), startLevel);
    } else {
        LOG.info("Installing bundle {} at default start level", f.getName());
    }
    return this.doPost(URL_BUNDLES, builder.build(), 302);
}
Also used : MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder)

Example 12 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project weixin-java-tools by chanjarster.

the class MaterialUploadRequestExecutor method execute.

public WxMpMaterialUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, WxMpMaterial material) throws WxErrorException, ClientProtocolException, IOException {
    HttpPost httpPost = new HttpPost(uri);
    if (httpProxy != null) {
        RequestConfig response = RequestConfig.custom().setProxy(httpProxy).build();
        httpPost.setConfig(response);
    }
    if (material != null) {
        File file = material.getFile();
        if (file == null || !file.exists()) {
            throw new FileNotFoundException();
        }
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("media", new InputStreamBody(bufferedInputStream, material.getName())).setMode(HttpMultipartMode.RFC6532);
        Map<String, String> form = material.getForm();
        if (material.getForm() != null) {
            multipartEntityBuilder.addTextBody("description", WxGsonBuilder.create().toJson(form));
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
    }
    CloseableHttpResponse response = httpclient.execute(httpPost);
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
        throw new WxErrorException(error);
    } else {
        return WxMpMaterialUploadResult.fromJson(responseContent);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) WxError(me.chanjar.weixin.common.bean.result.WxError) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) WxErrorException(me.chanjar.weixin.common.exception.WxErrorException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody)

Example 13 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project UltimateAndroid by cymcsg.

the class HttpUtils method uploadFiles.

public static String uploadFiles(String url, List<NameValuePair> paramsList, String fileParams, List<File> files) throws Exception {
    String result = "";
    try {
        DefaultHttpClient mHttpClient;
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
        mHttpClient = new DefaultHttpClient(params);
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (BasicUtils.judgeNotNull(paramsList)) {
            for (NameValuePair nameValuePair : paramsList) {
                entityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
            }
        }
        // entityBuilder.addBinaryBody(fileParams, file);
        for (File f : files) {
            if (f != null && f.exists())
                entityBuilder.addBinaryBody(fileParams, f);
        }
        HttpEntity entity = entityBuilder.build();
        httpPost.setEntity(entity);
        HttpResponse httpResp = mHttpClient.execute(httpPost);
        if (httpResp.getStatusLine().getStatusCode() == 200) {
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
            Logs.d("HttpPost success :");
            Logs.d(result);
        } else {
            Logs.d("HttpPost failed" + "    " + httpResp.getStatusLine().getStatusCode() + "   " + EntityUtils.toString(httpResp.getEntity(), "UTF-8"));
            result = "HttpPost failed";
        }
    } catch (ConnectTimeoutException e) {
        result = "ConnectTimeoutException";
        Logs.e("HttpPost overtime:  " + "");
    } catch (Exception e) {
        e.printStackTrace();
        Logs.e(e, "");
        result = "Exception";
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) File(java.io.File) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 14 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project camel by apache.

the class CxfRsConsumerSimpleBindingTest method testMultipartPostWithoutParameters.

@Test
public void testMultipartPostWithoutParameters() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart/withoutParameters");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT);
    builder.addBinaryBody("part1", new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), ContentType.create("image/jpeg"), "java.jpg");
    builder.addBinaryBody("part2", new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), ContentType.create("image/jpeg"), "java.jpg");
    StringWriter sw = new StringWriter();
    jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
    builder.addTextBody("body", sw.toString(), ContentType.create("text/xml", Consts.UTF_8));
    post.setEntity(builder.build());
    HttpResponse response = httpclient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) StringWriter(java.io.StringWriter) Customer(org.apache.camel.component.cxf.jaxrs.simplebinding.testbean.Customer) HttpResponse(org.apache.http.HttpResponse) File(java.io.File) Test(org.junit.Test)

Example 15 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project fb-botmill by BotMill.

the class FbBotMillNetworkController method postFormDataMessage.

// TODO: used for attaching files but not working at the moment.
/**
	 * POSTs a message as a JSON string to Facebook.
	 *
	 * @param recipient
	 *            the recipient
	 * @param type
	 *            the type
	 * @param file
	 *            the file
	 */
public static void postFormDataMessage(String recipient, AttachmentType type, File file) {
    String pageToken = FbBotMillContext.getInstance().getPageToken();
    // If the page token is invalid, returns.
    if (!validatePageToken(pageToken)) {
        return;
    }
    // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
    HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken);
    FileBody filedata = new FileBody(file);
    StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}", ContentType.MULTIPART_FORM_DATA);
    StringBody messagePart = new StringBody("{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}", ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.STRICT);
    builder.addPart("recipient", recipientPart);
    builder.addPart("message", messagePart);
    // builder.addPart("filedata", filedata);
    builder.addBinaryBody("filedata", file);
    builder.setContentType(ContentType.MULTIPART_FORM_DATA);
    // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    // Logs the raw JSON for debug purposes.
    BufferedReader br;
    // post.addHeader("Content-Type", "multipart/form-data");
    try {
        // br = new BufferedReader(new InputStreamReader(
        // ())));
        Header[] allHeaders = post.getAllHeaders();
        for (Header h : allHeaders) {
            logger.debug("Header {} ->  {}", h.getName(), h.getValue());
        }
    // String output = br.readLine();
    } catch (Exception e) {
        e.printStackTrace();
    }
// postInternal(post);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) Header(org.apache.http.Header) StringBody(org.apache.http.entity.mime.content.StringBody) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException)

Aggregations

MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)24 HttpPost (org.apache.http.client.methods.HttpPost)10 StringBody (org.apache.http.entity.mime.content.StringBody)7 File (java.io.File)6 IOException (java.io.IOException)5 Test (org.junit.Test)5 IRI (org.apache.clerezza.commons.rdf.IRI)4 HttpEntity (org.apache.http.HttpEntity)4 HttpResponse (org.apache.http.HttpResponse)3 InputStreamBody (org.apache.http.entity.mime.content.InputStreamBody)3 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 StringWriter (java.io.StringWriter)2 Charset (java.nio.charset.Charset)2 LinkedHashMap (java.util.LinkedHashMap)2 Customer (org.apache.camel.component.cxf.jaxrs.simplebinding.testbean.Customer)2 Graph (org.apache.clerezza.commons.rdf.Graph)2 Header (org.apache.http.Header)2 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)2 ClientProtocolException (org.apache.http.client.ClientProtocolException)2