Java 类org.apache.http.entity.mime.MultipartEntityBuilder 实例源码

项目:cloud-ariba-partner-flow-extension-ext    文件:OpenApisEndpoint.java   
/**
 * Performs HTTP Post request with OAuth authentication for the endpoint
 * with the given path, with the given binary bodies as payload. Uses
 * multipart/mixed content type.
 * 
 * @param path
 *            the path to be called.
 * @param binaryBodies
 *            the payload.
 * @return the CloseableHttpResponse object.
 * @throws ClientProtocolException
 * @throws IOException
 */
CloseableHttpResponse executeHttpPost(String path, List<BinaryBody> binaryBodies)
        throws ClientProtocolException, IOException {
    logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR_WITH_BINARY_BODIES, baseUri, path);

    HttpPost httpPost = createHttpPost(baseUri + path);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MULTIPART_MIXED_BOUNDARY);

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    for (BinaryBody binaryBody : binaryBodies) {
        multipartEntityBuilder.addBinaryBody(binaryBody.getBinaryBodyName(), binaryBody.getFileStream(),
                ContentType.create(binaryBody.getMediaType()), binaryBody.getFileName());
    }

    HttpEntity httpEntity = multipartEntityBuilder.setBoundary(OpenApisEndpoint.BOUNDARY).build();
    httpPost.setEntity(httpEntity);

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpPost);

    logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR_WITH_BINARY_BODIES, baseUri, path);
    return response;
}
项目:Telejam    文件:SetWebhook.java   
@Override
public HttpEntity getHttpEntity() {
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();

  if (url != null)
    builder.addTextBody(URL_FIELD, url);

  if (certificate != null)
    builder.addBinaryBody(CERTIFICATE_FIELD, new File(certificate));

  if (maxConnections != null)
    builder.addTextBody(MAX_CONNECTIONS_FIELD, maxConnections.toString());

  if (allowedUpdates != null) {
    if (allowedUpdates.length == 0) {
      builder.addTextBody(ALLOWED_UPDATES_FIELD, "[]");
    } else {
      for (String allowedUpdate : allowedUpdates) {
        builder.addTextBody(ALLOWED_UPDATES_FIELD + "[]", allowedUpdate);
      }
    }
  }

  return builder.build();
}
项目:sling-org-apache-sling-testing-clients    文件:OsgiConsoleClient.java   
/**
 * 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);

}
项目:QuickHttp    文件:QuickHttpController.java   
private void setupMultipartEntity(HttpPost httpPost){
    if(isDebug){
        log("Request upload file:"+mFile.getName() +"  exists:"+ mFile.exists());
    }
    MultipartEntityBuilder entity = MultipartEntityBuilder.create()
            .seContentType(ContentType.MULTIPART_FORM_DATA)
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody(mName,mFile,ContentType.DEFAULT_BINARY,mFileName) //uploadFile对应服务端类的同名属性<File类型>
            .setCharset(DEFAULT_CHARSET);

    for (String key:mFileParames.keySet()) {
        String value = mFileParames.get(key);
        entity.addTextBody(key,value);
    }
    httpPost.setEntity(entity.build());
}
项目:slacklet    文件:SlackWebSocketSessionImpl.java   
private void postSlackCommandWithFile(Map<String, String> params, byte [] fileContent, String fileName, String command, SlackMessageHandleImpl handle) {
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme(SLACK_API_SCHEME).setHost(SLACK_API_HOST).setPath(SLACK_API_PATH+"/"+command);
    for (Map.Entry<String, String> arg : params.entrySet())
    {
        uriBuilder.setParameter(arg.getKey(),arg.getValue());
    }
    HttpPost request = new HttpPost(uriBuilder.toString());
    HttpClient client = getHttpClient();
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    try
    {
        builder.addBinaryBody("file",fileContent, ContentType.DEFAULT_BINARY,fileName);
        request.setEntity(builder.build());
        HttpResponse response = client.execute(request);
        String jsonResponse = ReaderUtils.readAll(new InputStreamReader(response.getEntity().getContent()));
        LOGGER.debug("PostMessage return: " + jsonResponse);
        ParsedSlackReply reply = SlackJSONReplyParser.decode(parseObject(jsonResponse),this);
        handle.setReply(reply);
    }
    catch (Exception e)
    {
        // TODO : improve exception handling
        e.printStackTrace();
    }
}
项目:tephra    文件:HttpImpl.java   
@Override
public String upload(String url, Map<String, String> requestHeaders, Map<String, String> parameters,
                     Map<String, File> files, String charset) {
    if (validator.isEmpty(files))
        return post(url, requestHeaders, parameters, charset);

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    ContentType contentType = ContentType.create("text/plain", context.getCharset(charset));
    if (!validator.isEmpty(parameters))
        parameters.forEach((key, value) -> entity.addTextBody(key, value, contentType));
    files.forEach(entity::addBinaryBody);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    postByEntity(url, requestHeaders, entity.build(), null, outputStream);

    return outputStream.toString();
}
项目:armorvox-client    文件:VxmlClientVerify.java   
@SneakyThrows
protected void addBody(MultipartEntityBuilder request, VxmlRequestTask task) {

    super.addBody(request, task);

    String id = task.getKey();
    if (task.getUtterances().isEmpty()) {
        task.addUtterance(String.format("%s/%s-2-%s-1.wav", id, id, parameters.getPrintName()));
    }
    File utterance = task.getUtterances().get(0);

    byte[] byteArray = IOUtils.toByteArray(new FileInputStream(utterance));
    request.addBinaryBody(REQ_UTTERANCE, byteArray);

    if (task.isFeatureVector()) {
        request.addTextBody(REQ_FEATURE_VECTOR, "true");
    }

    if (parameters.isTextPrompted()) {
        request.addTextBody(REQ_VOCAB, parameters.getVocab());
        String fileName = FilenameUtils.removeExtension(utterance.getPath());
        request.addTextBody(REQ_PHRASE, FileUtils.readFileToString(new File(String.format("%s.txt", fileName)), "UTF-8").trim());
    }

    summary.getByteCount().add(byteArray.length);
}
项目:armorvox-client    文件:VxmlClientDetectGender.java   
@SneakyThrows
protected void addBody(MultipartEntityBuilder request, VxmlRequestTask task) {

    super.addBody(request, task);

    long bytes = 0L;
    int idx = 0;

    for (File utterance : task.getUtterances()) {
        byte[] byteArray = IOUtils.toByteArray(new FileInputStream(utterance));
        request.addBinaryBody(REQ_UTTERANCE + (++idx), byteArray);
        bytes += byteArray.length;
    }
    if (task.isFeatureVector()) {
        request.addTextBody(REQ_FEATURE_VECTOR, "true");
    }
    summary.getByteCount().add(bytes);
}
项目:armorvox-client    文件:VxmlClientCheckQuality.java   
@SneakyThrows
@Override
protected void addBody(MultipartEntityBuilder request, VxmlRequestTask task) {

    super.addBody(request, task);

    request.addTextBody(REQ_PRINT_NAME, parameters.getPrintName());
    request.addTextBody(REQ_CHANNEL, parameters.getChannel());
    request.addTextBody(REQ_MODE, parameters.getMode());

    String fileName = FilenameUtils.removeExtension(task.getKey());
    if (parameters.isTextPrompted()) {
        request.addTextBody(REQ_PHRASE, FileUtils.readFileToString(new File(String.format("%s.txt", fileName)), "UTF-8").trim());
        request.addTextBody(REQ_VOCAB, parameters.getVocab());
    }
}
项目:yunpian-java-sdk    文件:VideoSmsApi.java   
/**
 * 
 * @param param
 *            apikey sign
 * @param layout
 *            {@code VideoLayout}
 * @param material
 *            视频资料zip文件
 * 
 * @return
 */
public Result<Template> addTpl(Map<String, String> param, String layout, byte[] material) {
    Result<Template> r = new Result<>();
    if (layout == null || material == null) return r.setCode(Code.ARGUMENT_MISSING);
    List<NameValuePair> list = param2pair(param, r, APIKEY, SIGN);
    if (r.getCode() != Code.OK) return r;

    Charset ch = Charset.forName(charset());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(ch).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (NameValuePair pair : list) {
        builder.addTextBody(pair.getName(), pair.getValue(), ContentType.create("text/plain", ch));
    }
    builder.addTextBody(LAYOUT, layout, ContentType.APPLICATION_JSON);
    builder.addBinaryBody(MATERIAL, material, ContentType.create("application/octet-stream", ch), null);

    StdResultHandler<Template> h = new StdResultHandler<>();
    try {
        return path("add_tpl.json").post(new HttpEntityWrapper(builder.build()), h, r);
    } catch (Exception e) {
        return h.catchExceptoin(e, r);
    }
}
项目:SignPicture    文件:Debug.java   
static void PostData() throws Exception {
    final String url = "https://upload.gyazo.com/api/upload";
    final HttpClient httpclient = new Downloader().client;

    // create the post request.
    final HttpPost httppost = new HttpPost(url);
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    final File f = new File("./src/main/resources/assets/signpic/textures/logo.png");
    builder.addBinaryBody("imagedata", f, ContentType.DEFAULT_BINARY, f.getName());
    builder.addTextBody("access_token", "4d080e95be741beba0b74653a872668326a79526784d2daed9190dc584bffad7");
    httppost.setEntity(builder.build());

    // execute request
    final HttpResponse response = httpclient.execute(httppost);
    final HttpEntity resEntity = response.getEntity();
    final InputStream stream = resEntity.getContent();

    System.out.println(response.getStatusLine());
    System.out.println(convertStreamToString(stream));

}
项目:weixin-java-tools    文件:ApacheMediaUploadRequestExecutor.java   
@Override
public WxMediaUploadResult execute(String uri, File file) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpPost.setConfig(config);
  }
  if (file != null) {
    HttpEntity entity = MultipartEntityBuilder
      .create()
      .addBinaryBody("media", file)
      .setMode(HttpMultipartMode.RFC6532)
      .build();
    httpPost.setEntity(entity);
  }
  try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }
    return WxMediaUploadResult.fromJson(responseContent);
  } finally {
    httpPost.releaseConnection();
  }
}
项目:XPages-Fusion-Application    文件:RestUtil.java   
public Response post(String url, String auth, JsonJavaObject postData, File fileUpload) throws JsonException, IOException, URISyntaxException {
    URI normUri = new URI(url).normalize();
    Request postRequest = Request.Post(normUri);

    //Add all headers
    if(StringUtil.isNotEmpty(auth)) {
        postRequest.addHeader("Authorization", auth);
    }

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("images_file", fileUpload, ContentType.APPLICATION_OCTET_STREAM, fileUpload.getName());

    if(postData != null) {
        String postDataString = JsonGenerator.toJson(JsonJavaFactory.instanceEx, postData);
        builder.addTextBody("classifier_ids", postDataString, ContentType.MULTIPART_FORM_DATA);
    }

    HttpEntity multipart = builder.build();
    postRequest.body(multipart);

    Response response = executor.execute(postRequest);
    return response;
}
项目:aerodrome-for-jet    文件:API.java   
/**
 * This will take a list of files, and attach them to the 
 * MultipartEntityBuilder instance
 * @param files Files to add
 * @param builder builder 
 */
private void setMultipartFileData( final Map<String,PostFile> files, 
  final MultipartEntityBuilder builder )
{
  //..Check for input files
  if ( files == null || builder == null )
    return;    

  for ( final String name : files.keySet())
  {
    //..Ensure the file exists
    final PostFile pf = files.get( name );

    if ( !pf.getFile().exists())
    {
      throw new IllegalArgumentException( 
        pf.getFile() + " (" + pf.getFilename() 
          + ") does not exist; cannot upload non-existent file." );
    }

    APILog.trace( LOG, "Added file", pf.getFile(), "(", pf.getFilename(), ")" );

    builder.addBinaryBody( name, pf.getFile(), pf.getContentType(), pf.getFilename());
  }
}
项目:Cognitive-SpeakerRecognition-Android    文件:SpeakerRestClientHelper.java   
/**
 * Adds a stream to an HTTP entity
 *
 * @param someStream Input stream to be added to an HTTP entity
 * @param fieldName A description of the entity content
 * @param fileName Name of the file attached as an entity
 * @return HTTP entity
 * @throws IOException Signals a failure while reading the input stream
 */
HttpEntity addStreamToEntity(InputStream someStream, String fieldName, String fileName) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int bytesRead;
    byte[] bytes = new byte[1024];
    while ((bytesRead = someStream.read(bytes)) > 0) {
        byteArrayOutputStream.write(bytes, 0, bytesRead);
    }
    byte[] data = byteArrayOutputStream.toByteArray();

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.setStrictMode();
    builder.addBinaryBody(fieldName, data, ContentType.MULTIPART_FORM_DATA, fileName);
    return builder.build();
}
项目:utils    文件:HttpClient.java   
private HttpPost postForm(String url, Map<String, String> params, Map<String, File> files, String charset) {
    if (StringUtils.isBlank(charset)) {
        charset = "UTF-8";
    }

    HttpPost httpPost = new HttpPost(url);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    if (null != params) {
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            builder.addTextBody(key, params.get(key), ContentType.create("text/plain", Charset.forName(charset)));
        }
    }
    if (CollectionUtils.isBlank(files)) {
        for (String filename : files.keySet()) {
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addBinaryBody(filename, files.get(filename), ContentType.DEFAULT_BINARY, filename);
        }
    }
    httpPost.setEntity(builder.build());

    return httpPost;
}
项目:code    文件:Request.java   
/**
 * Upload a binary file (using a post request).
 * 
 * @param path
 * @param params
 * @param filePath
 * @return
 */
public JSONObject upload(String path, String params, String filePath){
    String uri = this.endpoint + path;
    if(params != null || params != ""){
        uri += "?" + params;
    }
    HttpPost request = new HttpPost(uri);

    HttpEntity entity = (HttpEntity) MultipartEntityBuilder
            .create()
            .addBinaryBody("result", new File(filePath), 
                    ContentType.create("application/octet-stream"), 
                    "filename"
            )
            .build();

    request.setEntity(entity);  
    return processRequest(request);
}
项目:geeCommerce-Java-Shop-Software-and-PIM    文件:DefaultOptivoMailerService.java   
@Override
public String uploadAttacments(List<File> attachments) throws MailerServiceException, IOException {
    if (attachments == null || attachments.size() > 5) {
        throw new MailerServiceException("Attachments are absent or too much number to be upload.");
    }

    final MultipartEntityBuilder uploadMultipartEntity = MultipartEntityBuilder.create();
    addSystemParameters(uploadMultipartEntity);

    Map<String, Object> params = new LinkedHashMap<>();
    List<File> objects = Collections.emptyList();
    attachments.stream().forEach(attachment -> objects.add(attachment));
    params.put("bmFile", objects);

    String response = invoke(CMD_UPLOADPERSONALIZEDATTACHMENTS, app.cpStr_(Configuration.BM_MAILSERVICE_AUTH_CODE),
        params);
    if (!response.startsWith("ok:")) {
        throw new MailerServiceException(response);
    } else {
        return response.replace("ok: ", "");
    }
}
项目:geeCommerce-Java-Shop-Software-and-PIM    文件:DefaultOptivoMailerService.java   
private void addSystemParameters(MultipartEntityBuilder builder) {
    String bmSuccessUrl = app.cpStr_(Configuration.BM_SUCCESS_URL);
    if (StringUtils.isNotBlank(bmSuccessUrl)) {
        builder.addTextBody("bmSuccessUrl", bmSuccessUrl, contentType);
    }

    String bmFailureUrl = app.cpStr_(Configuration.BM_FAILURE_URL);
    if (StringUtils.isNotBlank(bmFailureUrl)) {
        builder.addTextBody("bmFailureUrl", bmFailureUrl, contentType);
    }

    String bmUrl = app.cpStr_(Configuration.BM_URL);
    if (StringUtils.isNotBlank(bmUrl)) {
        builder.addTextBody("bmUrl", bmUrl, contentType);
    }

    String bmEncoding = app.cpStr_(Configuration.BM_ENCODING);
    if (StringUtils.isNotBlank(bmEncoding)) {
        builder.addTextBody("bmEncoding", bmEncoding, contentType);
    }

    String bmVerbose = app.cpStr_(Configuration.BM_VERBOSE);
    if (StringUtils.isNotBlank(bmVerbose)) {
        builder.addTextBody("bmVerbose", bmVerbose, contentType);
    }
}
项目:nio-multipart    文件:FileUploadClient.java   
public VerificationItems postForm(final Map<String, String> formParamValueMap, final String endpoint, final String boundary){

        final HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setHeader(MultipartController.VERIFICATION_CONTROL_HEADER_NAME, MultipartController.VERIFICATION_CONTROL_FORM);
        try {

            for (Map.Entry<String, String> param : formParamValueMap.entrySet()) {
                HttpEntity httpEntity = MultipartEntityBuilder
                        .create()
                        .setBoundary(boundary)
                        .setContentType(ContentType.MULTIPART_FORM_DATA)
                        //.addPart(FormBodyPartBuilder.create().addField(param.getKey(), param.getValue()).build())
                        .addPart(param.getKey(), new StringBody(param.getValue()))
                        .build();
                httpPost.setEntity(httpEntity);
            }

        }catch (Exception e){
            throw new IllegalStateException("Error preparing the post request", e);
        }
        return post(httpPost);
    }
项目:product-ei    文件:ActivitiRestClient.java   
/**
 * This Method is used to deploy BPMN packages to the BPMN Server
 *
 * @param fileName The name of the Package to be deployed
 * @param filePath The location of the BPMN package to be deployed
 * @throws java.io.IOException
 * @throws org.json.JSONException
 * @returns String array with status, deploymentID and Name
 */
public String[] deployBPMNPackage(String filePath, String fileName)
        throws RestClientException, IOException, JSONException {
    String url = serviceURL + "repository/deployments";
    DefaultHttpClient httpClient = getHttpClient();
    HttpPost httpPost = new HttpPost(url);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", new File(filePath),
                          ContentType.MULTIPART_FORM_DATA, fileName);
    HttpEntity multipart = builder.build();
    httpPost.setEntity(multipart);
    HttpResponse response = httpClient.execute(httpPost);
    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    if (status.contains(Integer.toString(HttpStatus.SC_CREATED)) || status.contains(Integer.toString(HttpStatus.SC_OK))) {
        String deploymentID = jsonResponseObject.getString(ID);
        String name = jsonResponseObject.getString(NAME);
        return new String[]{status, deploymentID, name};
    } else if (status.contains(Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR))) {
        String errorMessage = jsonResponseObject.getString("errorMessage");
        throw new RestClientException(errorMessage);
    } else {
        throw new RestClientException("Failed to deploy package " + fileName);
    }
}
项目:yacy_grid_mcp    文件:ClientConnection.java   
/**
 * POST request
 * @param urlstring
 * @param map
 * @param useAuthentication
 * @throws ClientProtocolException 
 * @throws IOException
 */
public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication) throws ClientProtocolException, IOException {
    this.request = new HttpPost(urlstring);        
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (Map.Entry<String, byte[]> entry: map.entrySet()) {
        entityBuilder.addBinaryBody(entry.getKey(), entry.getValue());
    }
    ((HttpPost) this.request).setEntity(entityBuilder.build());
    this.request.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
    this.init();
}
项目:QMark    文件:ClientMultipartFormPost.java   
public static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  //如果有SocketTimeoutException等情况,可修改这个枚举
    //builder.setCharset(Charset.forName("UTF-8")); //不要用这个,会导致服务端接收不到参数
    if (params != null && params.size() > 0) {
        for (NameValuePair p : params) {
            builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8"));
        }
    }
    if (files != null && files.size() > 0) {
        Set<Entry<String, File>> entries = files.entrySet();
        for (Entry<String, File> entry : entries) {
            builder.addPart(entry.getKey(), new FileBody(entry.getValue()));
        }
    }
    return builder.build();
}
项目:framework    文件:HttpUtils.java   
/**
 * 上传文件
 *
 * @param url  URL
 * @param name 文件的post参数名称
 * @param file 上传的文件
 * @return
 */
public static String postFile(String url, String name, File file) {
    try {
        HttpEntity reqEntity = MultipartEntityBuilder.create().addBinaryBody(name, file).build();
        Request request = Request.Post(url);
        request.body(reqEntity);
        HttpEntity resEntity = request.execute().returnResponse().getEntity();
        return resEntity != null ? EntityUtils.toString(resEntity) : null;
    } catch (Exception e) {
        logger.error("postFile请求异常," + e.getMessage() + "\n post url:" + url);
        e.printStackTrace();
    }
    return null;
}
项目:mtgo-best-bot    文件:BotCameraService.java   
public Long saveBotCam(BotCamera botCamera) {
    HttpEntity entity = MultipartEntityBuilder
            .create()
            .addPart("file", new ByteArrayBody(botCamera.getScreenShot(), "botSnapshot"))
            .build();

    Long idResponse = -1L;

    try {
        HttpPost httpPost = new HttpPost(apiUrl + BotCameraController.ENDPOINT_ROINT + "/" + botCamera.getPlayerBot().getName());
        httpPost.setEntity(entity);
        HttpResponse response = uploadHttpClient.execute(httpPost);
        ResponseHandler<String> handler = new BasicResponseHandler();

        if(response != null &&
            response.getStatusLine() != null &&
            response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {

            final String rawResult = handler.handleResponse(response);

            idResponse = Long.parseLong(rawResult);
        } else {
            log.error("Failed to upload pictar!");
            log.error("Headers received: " + Arrays.stream(response.getAllHeaders()).map(header -> new String(header.getName() + ": " + header.getValue()))
                                                                                    .reduce("", (result, next) -> System.lineSeparator() + next));
            log.error("Body received: " + System.lineSeparator() + handler.handleResponse(response));
        }
    } catch (IOException e) {
        log.error("Failed to upload pictar!");
        log.error(e.getMessage());
    }

    return idResponse;
}
项目:httpclient    文件:RestClient.java   
@SuppressWarnings("unchecked")
private HttpEntity createFileEntity(Object files) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (Entry<String, Object> entry : ((Map<String, Object>) files).entrySet()) {
        if (new File(entry.getValue().toString()).exists()) {
            builder.addPart(entry.getKey(),
                    new FileBody(new File(entry.getValue().toString()), ContentType.DEFAULT_BINARY));
        } else {
            builder.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), ContentType.DEFAULT_TEXT));
        }
    }
    return builder.build();
}
项目:ibm-cloud-devops    文件:PublishTest.java   
/**
 * * Send POST request to DLMS back end with the result file
 * @param bluemixToken - the Bluemix token
 * @param contents - the result file
 * @param jobUrl -  the build url of the build job in Jenkins
 * @param timestamp
 * @return - response/error message from DLMS
 */
public String sendFormToDLMS(String bluemixToken, FilePath contents, String lifecycleStage, String jobUrl, String timestamp) throws IOException {

    // create http client and post method
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost postMethod = new HttpPost(this.dlmsUrl);

    postMethod = addProxyInformation(postMethod);
    // build up multi-part forms
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    if (contents != null) {

        File file = new File(root, contents.getName());
        FileBody fileBody = new FileBody(file);
        builder.addPart("contents", fileBody);


        builder.addTextBody("test_artifact", file.getName());
        if (this.isDeploy) {
            builder.addTextBody("environment_name", environmentName);
        }
        //Todo check the value of lifecycleStage
        builder.addTextBody("lifecycle_stage", lifecycleStage);
        builder.addTextBody("url", jobUrl);
        builder.addTextBody("timestamp", timestamp);

        String fileExt = FilenameUtils.getExtension(contents.getName());
        String contentType;
        switch (fileExt) {
            case "json":
                contentType = CONTENT_TYPE_JSON;
                break;
            case "xml":
                contentType = CONTENT_TYPE_XML;
                break;
            default:
                return "Error: " + contents.getName() + " is an invalid result file type";
        }

        builder.addTextBody("contents_type", contentType);
        HttpEntity entity = builder.build();
        postMethod.setEntity(entity);
        postMethod.setHeader("Authorization", bluemixToken);
    } else {
        return "Error: File is null";
    }


    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(postMethod);
        // parse the response json body to display detailed info
        String resStr = EntityUtils.toString(response.getEntity());
        JsonParser parser = new JsonParser();
        JsonElement element =  parser.parse(resStr);

        if (!element.isJsonObject()) {
            // 401 Forbidden
            return "Error: Upload is Forbidden, please check your org name. Error message: " + element.toString();
        } else {
            JsonObject resJson = element.getAsJsonObject();
            if (resJson != null && resJson.has("status")) {
                return String.valueOf(response.getStatusLine()) + "\n" + resJson.get("status");
            } else {
                // other cases
                return String.valueOf(response.getStatusLine());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}
项目:visitormanagement    文件:HttpConnectorHelper.java   
/** 
 * 
 * @param map
 * 
 * @return HttpEntity
 */
public static HttpEntity buildEntityWithBodyParam(Map<String, String> map) {
    if (MapUtils.isEmpty(map)) {
        return null;
    }
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    map.forEach((k, v) -> builder.addTextBody(k, v));
    return builder.build();
}
项目:visitormanagement    文件:HttpConnectorHelper.java   
/**
 * @param buildMap
 * @param partParam
 * 
 * @return HttpEntity
 */
public static HttpEntity buildMultiPartEntity(Map<String, String> buildMap, Map<String, ContentBody> partParam) {
    if (MapUtils.isEmpty(buildMap)) {
        return null;
    }
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    buildMap.forEach((k, v) -> builder.addTextBody(k, v));
    if (MapUtils.isNotEmpty(partParam)) {
        partParam.forEach((k, v) -> builder.addPart(k, v)); 
    }
    return builder.build();
}
项目:ats-framework    文件:HttpClient.java   
private void constructRequestBody() {

        // we have work to do here only when using multipart body
        if (requestBodyParts.size() > 0) {
            try {
                MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
                for (HttpBodyPart part : requestBodyParts) {
                    entityBuilder.addPart(part.getName(), part.constructContentBody());
                }
                requestBody = entityBuilder.build();
            } catch (Exception e) {
                throw new HttpException("Exception trying to create a multipart message.", e);
            }
        }
    }
项目:Telejam    文件:SendMediaGroup.java   
@Override
public HttpEntity getHttpEntity() {
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();

  if (chatId != null)
    builder.addTextBody(CHAT_ID_FIELD, chatId);

  if (media != null) {
    builder.addTextBody(MEDIA_FIELD, TelegramObject.gson.toJson(media));
    for (InputMedia inputMedia : media) {
      if (inputMedia.getFile().isPresent()) {
        InputStream file = inputMedia.getFile().get();
        String fileAttachName = inputMedia.getFileAttachName()
            .orElseThrow(NullPointerException::new);
        builder.addBinaryBody(fileAttachName, file, ContentType.APPLICATION_OCTET_STREAM, fileAttachName);
      }
    }
  }

  if (disableNotification != null)
    builder.addTextBody(DISABLE_NOTIFICATION_FIELD, disableNotification.toString());

  if (replyToMessageId != null)
    builder.addTextBody(REPLY_TO_MESSAGE_ID_FIELD, replyToMessageId.toString());

  return builder.build();
}
项目:Telejam    文件:SetChatPhoto.java   
@Override
public HttpEntity getHttpEntity() {
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();

  if(chatId != null)
      builder.addTextBody(CHAT_ID_FIELD, chatId);

  if(photo != null)
      builder.addBinaryBody(PHOTO_FIELD, photo, ContentType.APPLICATION_OCTET_STREAM, fileName);

  return builder.build();
}
项目:setra    文件:MvcTest.java   
@Test
public void invalidFormSubmit() throws Exception {
    // message missing
    final String boundary = "------TestBoundary" + UUID.randomUUID();
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create()
        .setBoundary(boundary);

    mockMvc.perform(post("/send")
        .content(ByteStreams.toByteArray(builder.build().getContent()))
        .contentType(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + boundary))
        .andExpect(status().isOk())
        .andExpect(content().contentType("text/html;charset=UTF-8"))
        .andExpect(model().hasErrors());
}
项目:sling-org-apache-sling-testing-clients    文件:SlingClient.java   
/**
 * Uploads a file to the repository. It creates a leaf node typed {@code nt:file}. The intermediary nodes are created with
 * type "sling:OrderedFolder" if parameter {@code createFolders} is true
 *
 * @param file           the file to be uploaded
 * @param mimeType       the MIME Type of the file
 * @param toPath         the complete path of the file in the repository including file name
 * @param createFolders  if true, all non existing parent nodes will be created using node type {@code sling:OrderedFolder}
 * @param expectedStatus list of expected HTTP Status to be returned, if not set, 201 is assumed.
 * @return               the response
 * @throws ClientException if something fails during the request/response cycle
 */
public SlingHttpResponse upload(File file, String mimeType, String toPath, boolean createFolders, int... expectedStatus)
        throws ClientException {
    // Determine filename and parent folder, depending on whether toPath is a folder or a file
    String toFileName;
    String toFolder;
    if (toPath.endsWith("/")) {
        toFileName = file.getName();
        toFolder = toPath;
    } else {
        toFileName = getNodeNameFromPath(toPath);
        toFolder = getParentPath(toPath);
    }

    if (createFolders) {
        createNodeRecursive(toFolder, "sling:OrderedFolder");
    }

    if (mimeType == null) {
        mimeType = "application/octet-stream";
    }

    HttpEntity entity = MultipartEntityBuilder.create()
            .addBinaryBody(toFileName, file, ContentType.create(mimeType), toFileName)
            .build();

    // return the sling response
    return this.doPost(toFolder, entity, HttpUtils.getExpectedStatus(SC_CREATED, expectedStatus));
}
项目:Wechat-Group    文件:MediaImgUploadRequestExecutor.java   
@Override
public WxMediaImgUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File data) throws WxErrorException, IOException {
  if (data == null) {
    throw new WxErrorException(WxError.newBuilder().setErrorMsg("文件对象为空").build());
  }

  HttpPost httpPost = new HttpPost(uri);
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpPost.setConfig(config);
  }

  HttpEntity entity = MultipartEntityBuilder
    .create()
    .addBinaryBody("media", data)
    .setMode(HttpMultipartMode.RFC6532)
    .build();
  httpPost.setEntity(entity);
  httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());

  try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }

    return WxMediaImgUploadResult.fromJson(responseContent);
  }
}
项目:Wechat-Group    文件:MediaUploadRequestExecutor.java   
@Override
public WxMediaUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File file) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpPost.setConfig(config);
  }
  if (file != null) {
    HttpEntity entity = MultipartEntityBuilder
            .create()
            .addBinaryBody("media", file)
            .setMode(HttpMultipartMode.RFC6532)
            .build();
    httpPost.setEntity(entity);
    httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
  }
  try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }
    return WxMediaUploadResult.fromJson(responseContent);
  } finally {
    httpPost.releaseConnection();
  }
}
项目:c4sg-services    文件:SlackUtils.java   
public static HttpEntity createMultipartFormEntity(Map<String, String> parameters, InputStream is) {
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));

    multipartEntityBuilder.addBinaryBody("file", is, ContentType.create("application/octet-stream"), "file");
    for (Entry<String, String> entry : parameters.entrySet()) {
        multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue());
    }
    return multipartEntityBuilder.build();
}
项目:pjbank-java-sdk    文件:ContaDigitalManager.java   
/**
 * Retorna a lista de anexos de uma transação com ou sem filtro de tipo
 * @param idTransacao: Código da transação à ser consultada
 * @param arquivo: Arquivo à ser anexado (imagem [JPEG/PNG] ou documento [PDF])
 * @param tipoAnexo: Tipo de anexo à ser enviado
 * @return boolean
 */
public boolean attachFileToTransaction(String idTransacao, File arquivo, TipoAnexo tipoAnexo) throws IOException,
        PJBankException {
    Set<String> extensoesPermitidas = new HashSet<>();
    extensoesPermitidas.add("pdf");
    extensoesPermitidas.add("jpg");
    extensoesPermitidas.add("jpeg");
    extensoesPermitidas.add("png");

    if (!extensoesPermitidas.contains(FilenameUtils.getExtension(arquivo.getName()))) {
        throw new IllegalArgumentException("O arquivo a ser anexado em uma transação deve estar no formato PDF, JPG," +
                " JPEG ou PNG, sendo assim um documento ou uma imagem.");
    }

    PJBankClient client = new PJBankClient(this.endPoint.concat("/transacoes/").concat(idTransacao).concat("/documentos"));
    HttpPost httpPost = client.getHttpPostClient();
    httpPost.addHeader("x-chave-conta", this.chave);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    //FileBody fileBody = new FileBody(arquivo);
    StringBody stringBody = new StringBody(tipoAnexo.getName(), ContentType.TEXT_PLAIN);
    //builder.addPart("arquivos", fileBody);
    builder.addBinaryBody("arquivos", arquivo,
            ContentType.APPLICATION_OCTET_STREAM, arquivo.getName());
    builder.addPart("tipo", stringBody);

    httpPost.setEntity(builder.build());

    return client.doRequest(httpPost).getStatusLine().getStatusCode() == 201;
}
项目:flow-platform    文件:ReportManager.java   
public boolean cmdLogUploadSync(final String cmdId, final Path path) {
    if (!Config.isUploadLog()) {
        LOGGER.trace("Log upload toggle is disabled");
        return true;
    }

    HttpEntity entity = MultipartEntityBuilder.create()
        .addPart("file", new FileBody(path.toFile(), ContentType.create("application/zip")))
        .addPart("cmdId", new StringBody(cmdId, ContentType.create("text/plain", Charsets.UTF_8)))
        .setContentType(ContentType.MULTIPART_FORM_DATA)
        .build();

    String url = Config.agentSettings().getCmdLogUrl();
    HttpResponse<String> response = HttpClient.build(url)
        .post(entity)
        .retry(5)
        .bodyAsString();

    if (!response.hasSuccess()) {
        LOGGER.warn("Fail to upload zipped cmd log to : %s ", url);
        return false;
    }

    LOGGER.trace("Zipped cmd log uploaded %s", path);
    return true;
}
项目:FCat    文件:HttpCallSSL.java   
@Override
public String uploadFile(String systemName, String entityName, String apiUrl, List<File> fileList, String requestParamInputName) throws IllegalStateException {
    HttpResponse response = null;
    HttpPost httpPost = getHttpPost();
    try {
        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        String[] urlAndParame = apiUrl.split("\\?");
        String apiUrlNoParame = urlAndParame[0];
        Map<String, String> parameMap = StrUtil.splitUrlToParameMap(apiUrl);
        Iterator<String> parameIterator = parameMap.keySet().iterator();

        httpPost.setURI(new URI(apiUrlNoParame));
        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        while (parameIterator.hasNext()) {
            String parameName = parameIterator.next();
            nvps.add(new BasicNameValuePair(parameName, parameMap.get(parameName)));
            multipartEntity.addPart(parameName, new StringBody(parameMap.get(parameName), ContentType.create("text/plain", Consts.UTF_8)));
        }

        if (!StrUtil.isBlank(systemName)) {
            multipartEntity.addPart("systemName", new StringBody(systemName, ContentType.create("text/plain", Consts.UTF_8)));
        }
        if (!StrUtil.isBlank(entityName)) {
            multipartEntity.addPart("entityName", new StringBody(entityName, ContentType.create("text/plain", Consts.UTF_8)));
        }
        // 多文件上传 获取文件数组前台标签name值
        if (!StrUtil.isBlank(requestParamInputName)) {
            multipartEntity.addPart("filesName", new StringBody(requestParamInputName, ContentType.create("text/plain", Consts.UTF_8)));
        }

        if (fileList != null) {
            for (int i = 0, size = fileList.size(); i < size; i++) {
                File file = fileList.get(i);
                multipartEntity.addBinaryBody(requestParamInputName, file, ContentType.DEFAULT_BINARY, file.getName());
            }
        }
        HttpEntity entity = multipartEntity.build();
        httpPost.setEntity(entity);

        response = httpClient.execute(httpPost);
        String statusCode = String.valueOf(response.getStatusLine().getStatusCode());
        if (statusCode.indexOf("20") == 0) {
            entity = response.getEntity();
            // String contentType = entity.getContentType().getValue();//
            // application/json;charset=ISO-8859-1
            return StrUtil.readStream(entity.getContent(), responseContextEncode);
        }  else {
            LOG.error("返回状态码:[" + statusCode + "]");
            return "返回状态码:[" + statusCode + "]";
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpPost.releaseConnection();
    }
    return null;
}