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:edu.scripps.fl.pubchem.web.session.PCWebSession.java

/**
 * //  www  .j a  va 2 s  . com
 * Returns an SDF file of substances in an AID.<br>
 * It only works if on-hold SIDs are from your own center. If you submit
 * AIDs for other centers, you cannot download their SIDs!
 * 
 * @param aid
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public InputStream getAssaySDF(int aid) throws Exception {
    String page = getDataTablePage(aid);
    String url = getLinkFromJavaScript(page, "Substance Structure");
    Document document = getDocument(url);
    MultipartEntity entity = new MultipartEntity();
    Node formNode = document.selectSingleNode("//form[1]");
    addFormParts(formNode, entity, new HashSet(Arrays.asList("savejob")));
    document = new WaitOnRequestId(postPage("http://" + SITE + "/pc_fetch/pc_fetch.cgi", entity)).asDocument();
    return getFtpLinkAsStream(document);
}

From source file:code.google.restclient.client.HitterClient.java

private MultipartEntity getMultipartEntity(ViewRequest req) throws RCException {
    MultipartEntity reqEntity = new MultipartEntity();
    Map<String, String> params = req.getParams();
    String paramValue = null;/*from  w  w w . j  a  v a 2  s  . c om*/
    StringBody stringBody = null;

    try {
        for (String paramName : params.keySet()) {
            paramValue = params.get(paramName);
            stringBody = new StringBody(paramValue, Charset.forName(RCConstants.DEFAULT_CHARSET));
            reqEntity.addPart(paramName, stringBody);
        }
        String fileParamName = req.getFileParamName();
        File selectedFile = new File(req.getFilePath());

        if (selectedFile.exists() && !RCUtil.isEmpty(fileParamName)) {
            String mimeType = MimeTypeUtil.getMimeType(req.getFilePath());
            FileBody fileBody = new FileBody(selectedFile, mimeType);
            reqEntity.addPart(fileParamName, fileBody);
        }
    } catch (UnsupportedEncodingException e) {
        throw new RCException(
                "getMultipartEntity(): Could not prepare multipart entity due to unsupported encoding", e);
    }
    return reqEntity;
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Sends data to create and train a classifier, and returns information about the new
 * classifier. The status has the value of `Training` when the operation is
 * successful, and might remain at this status for a while.
 * /*from   w w  w  . j a v a2  s  .c o m*/
 * @param name
 *            the classifier name
 * @param language
 *            IETF primary language for the classifier
 * @param trainingData
 *            The set of questions and their "keys" used to adapt a system to a domain
 *            (the ground truth)
 * @return the classifier
 * @see Classifier
 */
public Classifier createClassifier(final String name, final String language,
        final List<TrainingData> trainingData) {
    if (trainingData == null || trainingData.isEmpty())
        throw new IllegalArgumentException("trainingData can not be null or empty");

    JsonObject contentJson = new JsonObject();

    contentJson.addProperty("language", language == null ? LANGUAGE_EN : language);

    if (name != null && !name.isEmpty()) {
        contentJson.addProperty("name", name);
    }

    try {

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("training_data",
                new StringBody(TrainingDataUtils.toCSV(trainingData.toArray(new TrainingData[0]))));
        reqEntity.addPart("training_metadata", new StringBody(contentJson.toString()));

        HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build();
        HttpHost proxy = new HttpHost("10.100.1.124", 3128);
        ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
        HttpResponse response = execute(request);
        return ResponseUtil.getObject(response, Classifier.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:br.itecbrazil.serviceftpcliente.model.ThreadEnvio.java

private void enviarArquivo(File arquivo, Config config) {
    if (gravarBackup(arquivo)) {
        logger.info("Enviando arquivo " + arquivo.getName() + ". Thread: " + Thread.currentThread().getName());
        try {/*  w ww .jav  a2s.  c o m*/
            HttpClient httpclient = new org.apache.http.impl.client.DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://" + config.getHost() + "/upload");
            httppost.setHeader("X-Requested-With", "XMLHttpRequest");

            MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("id", new StringBody(config.getUsuario()));
            mpEntity.addPart("arquivo", new FileBody(arquivo));

            httppost.setEntity(mpEntity);
            System.out.println("executing request " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            if (response.getStatusLine().getStatusCode() == 200) {
                logger.info("Arquivo arquivo " + arquivo.getName() + " enviado com sucesso. Thread: "
                        + Thread.currentThread().getName());
                atualizarDadoDeEnvio(arquivo);
                arquivo.delete();
                logger.info("Arquivo deletado " + arquivo.getName() + " do diretorio de envio. Thread: "
                        + Thread.currentThread().getName());
            }

        } catch (MalformedURLException ex) {
            loggerExceptionEnvio.info(ex);
        } catch (IOException ex) {
            loggerExceptionEnvio.info(ex);
        }
    }
}

From source file:com.brightcove.com.uploader.helper.MediaManagerHelper.java

public Long uploadFile(URI uri, File f, DefaultHttpClient client)
        throws HttpException, IOException, URISyntaxException, ParserConfigurationException, SAXException {
    mLog.info("using " + uri.getHost() + " on port " + uri.getPort() + " for MM upload");

    HttpPost method = new HttpPost(uri);
    MultipartEntity entityIn = new MultipartEntity();
    entityIn.addPart("FileName", new StringBody(f.getName(), Charset.forName("UTF-8")));

    FileBody fileBody = null;/*from w w w .ja va2s.  co m*/

    if (f != null) {
        fileBody = new FileBody(f);
    }

    if (f != null) {
        entityIn.addPart(f.getName(), fileBody);
    }

    entityIn.addPart("Upload", new StringBody("Submit Query", Charset.forName("UTF-8")));
    method.setEntity(entityIn);

    if (client != null) {
        return executeUpload(method, client);
    }

    return null;
}

From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java

private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken)
        throws URISyntaxException, UnsupportedEncodingException {
    String host = msgRequest.getTargetHost();
    if (host == null)
        throw new URISyntaxException(host, "null URI");
    if (!host.endsWith("/"))
        host += '/';
    String address = msgRequest.getTargetAddress();
    if (address == null)
        address = "";
    if (address.startsWith("/"))
        address = address.substring(1);/*from  w  w w  . ja v  a 2  s  .c o m*/
    String uriString = host + address;
    try {
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (MalformedURLException e) {
        throw new URISyntaxException(uriString, e.getMessage());
    }
    if (msgRequest.getQuery() != null)
        uriString += "?" + msgRequest.getQuery();

    //      new URI(uriString);

    HttpRequestBase request = null;
    if (msgRequest.getMethod().equals(Method.POST)) {
        HttpPost post = new HttpPost(uriString);
        HttpEntity httpEntity = null;
        if (msgRequest.getRequestParams() != null) {
            // if body and requestparams are either not null there is an
            // exception
            if (msgRequest.getBody() != null && msgRequest != null) {
                throw new IllegalArgumentException("body and requestParams cannot be either populated");
            }
            httpEntity = new MultipartEntity();

            for (RequestParam param : msgRequest.getRequestParams()) {
                if (param.getParamName() == null || param.getParamName().trim().length() == 0) {
                    throw new IllegalArgumentException("paramName cannot be null or empty");
                }
                if (param instanceof FileRequestParam) {
                    FileRequestParam fileparam = (FileRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody(
                            fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename()));
                }
                if (param instanceof ObjectRequestParam) {
                    ObjectRequestParam objectparam = (ObjectRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(),
                            new StringBody(convertObject(objectparam.getVars())));
                }
            }
            // mpe.addPart("file",
            // new ByteArrayBody(msgRequest.getFileContent(), ""));
            // post.setEntity(mpe);
        }
        if (msgRequest.getBody() != null) {
            httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            ((StringEntity) httpEntity).setContentType(msgRequest.getContentType());
        }
        post.setEntity(httpEntity);
        request = post;
    } else if (msgRequest.getMethod().equals(Method.PUT)) {
        HttpPut put = new HttpPut(uriString);
        if (msgRequest.getBody() != null) {
            StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            se.setContentType(msgRequest.getContentType());
            put.setEntity(se);
        }
        request = put;
    } else if (msgRequest.getMethod().equals(Method.DELETE)) {
        request = new HttpDelete(uriString);
    } else {
        // default: GET
        request = new HttpGet(uriString);
    }

    Map<String, String> headers = new HashMap<String, String>();

    // default headers
    if (appToken != null) {
        headers.put(RequestHeader.APP_TOKEN.toString(), appToken);
    }
    if (authToken != null) {
        // is here for compatibility
        headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken);
        headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken);
    }
    headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType());

    if (msgRequest.getCustomHeaders() != null) {
        headers.putAll(msgRequest.getCustomHeaders());
    }

    for (String key : headers.keySet()) {
        request.addHeader(key, headers.get(key));
    }

    return request;
}

From source file:org.anon.smart.smcore.test.channel.upload.TestUploadEvent.java

private void uploadFile(String file) {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:9020" + "/errortenant/ErrorCases/UploadEvent");

    FileBody bin = new FileBody(new File(file));

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("bin", bin);

    httppost.setEntity(reqEntity);//from  w  w  w.ja  va  2 s. co  m

    System.out.println("executing request " + httppost.getRequestLine());
    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    String response = null;
    try {
        response = httpclient.execute(httppost, responseHandler);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
}

From source file:org.apache.sling.testing.tools.sling.SlingClient.java

/** Updates a node at specified path, with optional properties
*//*w  w  w  . j  a va  2  s  .  c o  m*/
public void setProperties(String path, Map<String, Object> properties) throws IOException {
    final MultipartEntity entity = new MultipartEntity();
    // Add user properties
    if (properties != null) {
        for (Map.Entry<String, Object> e : properties.entrySet()) {
            entity.addPart(e.getKey(), new StringBody(e.getValue().toString()));
        }
    }

    final HttpResponse response = executor
            .execute(builder.buildPostRequest(path).withEntity(entity).withCredentials(username, password))
            .assertStatus(200).getResponse();
}

From source file:com.minws.frame.sdk.webqq.service.ApacheHttpService.java

/** {@inheritDoc} */
@Override//w ww. j  ava  2 s . c  om
public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener)
        throws QQException {
    try {
        URI uri = URI.create(request.getUrl());

        if (request.getMethod().equals("POST")) {
            HttpPost httppost = new HttpPost(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }

            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout());
            }

            if (request.getFileMap().size() > 0) {
                MultipartEntity entity = new MultipartEntity();
                String charset = request.getCharset();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    entity.addPart(key, new StringBody(value, Charset.forName(charset)));
                }

                Map<String, File> fileMap = request.getFileMap();
                for (String key : fileMap.keySet()) {
                    File value = fileMap.get(key);
                    entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value))));
                }
                httppost.setEntity(entity);
            } else if (request.getPostMap().size() > 0) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    list.add(new BasicNameValuePair(key, value));
                }
                httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset()));
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httppost.addHeader(key, headerMap.get(key));
            }
            QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener);
            QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar);
            QQHttpResponseCallback callback = new QQHttpResponseCallback(listener);
            Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback);
            return new ProxyFuture(future, consumer, producer);

        } else if (request.getMethod().equals("GET")) {
            HttpGet httpget = new HttpGet(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httpget.addHeader(key, headerMap.get(key));
            }
            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout());
            }

            return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget),
                    new QQHttpResponseConsumer(request, listener, cookieJar),
                    new QQHttpResponseCallback(listener));

        } else {
            throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod());
        }
    } catch (IOException e) {
        throw new QQException(QQErrorCode.IO_ERROR);
    }
}

From source file:com.halseyburgund.roundware.server.RWHttpManager.java

public static String uploadFile(String page, Properties properties, String fileParam, String file)
        throws Exception {
    if (D) {//  w w  w.  j ava  2s.  co m
        RWHtmlLog.i(TAG, "Starting upload of file: " + file, null);
    }

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);

    HttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost(page);
    MultipartEntity entity = new MultipartEntity();

    Iterator<Map.Entry<Object, Object>> i = properties.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) i.next();
        String key = (String) entry.getKey();
        String val = (String) entry.getValue();
        entity.addPart(key, new StringBody(val));
        if (D) {
            RWHtmlLog.i(TAG, "Added StringBody multipart for: '" + key + "' = '" + val + "'", null);
        }
    }

    File upload = new File(file);
    entity.addPart(fileParam, new FileBody(upload));
    if (D) {
        String msg = "Added FileBody multipart for: '" + fileParam + "' = <'" + upload.getAbsolutePath()
                + ", size: " + upload.length() + " bytes >'";
        RWHtmlLog.i(TAG, msg, null);
    }

    request.setEntity(entity);

    if (D) {
        RWHtmlLog.i(TAG, "Sending HTTP request...", null);
    }

    HttpResponse response = httpClient.execute(request);

    int st = response.getStatusLine().getStatusCode();

    if (st == HttpStatus.SC_OK) {
        StringBuffer sbResponse = new StringBuffer();
        InputStream content = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
            sbResponse.append(line);
        }
        content.close(); // this will also close the connection

        if (D) {
            RWHtmlLog.i(TAG, "Upload successful (HTTP code: " + st + ")", null);
            RWHtmlLog.i(TAG, "Server response: " + sbResponse.toString(), null);
        }

        return sbResponse.toString();
    } else {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        entity.writeTo(ostream);
        RWHtmlLog.e(TAG, "Upload failed (http code: " + st + ")", null);
        RWHtmlLog.e(TAG, "Server response: " + ostream.toString(), null);
        throw new Exception(HTTP_POST_FAILED + st);
    }
}