Java Code Examples for org.apache.http.entity.mime.MultipartEntityBuilder#addBinaryBody()

The following examples show how to use org.apache.http.entity.mime.MultipartEntityBuilder#addBinaryBody() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VideoSmsApi.java    From yunpian-java-sdk with MIT License 8 votes vote down vote up
/**
 * 
 * @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<>(new TypeToken<Result<Template>>() {}.getType());
    try {
        return path("add_tpl.json").post(new HttpEntityWrapper(builder.build()), h, r);
    } catch (Exception e) {
        return h.catchExceptoin(e, r);
    }
}
 
Example 2
Source File: Remote.java    From HongsCORE with MIT License 7 votes vote down vote up
private static void buildPart(MultipartEntityBuilder part, String n, Object v) {
    if (v instanceof ContentBody) {
        part.addPart(n, (ContentBody) v);
    } else
    if (v instanceof File) {
        part.addBinaryBody(n , (File) v);
    } else
    if (v instanceof byte[]) {
        part.addBinaryBody(n , (byte[]) v);
    } else
    if (v instanceof InputStream) {
        part.addBinaryBody(n , (InputStream) v);
    } else
    {
        part.addTextBody(n , String.valueOf(v));
    }
}
 
Example 3
Source File: HttpFluentService.java    From AthenaServing with Apache License 2.0 7 votes vote down vote up
/**
 * 构建POST方法请求参数
 * @return
 */
private HttpEntity buildPostParam(List<NameValuePair> nameValuePairs, List<File> files) {
    if(CollectionUtils.isEmpty(nameValuePairs) && CollectionUtils.isEmpty(files)) {
        return null;
    }
    if(!CollectionUtils.isEmpty(files)) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (File file : files) {
            builder.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
        }
        for (NameValuePair nameValuePair : nameValuePairs) {
            //设置ContentType为UTF-8,默认为text/plain; charset=ISO-8859-1,传递中文参数会乱码
            builder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), ContentType.create("text/plain", Consts.UTF_8));
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(nameValuePairs);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e.toString());
        }
    }
    return null;
}
 
Example 4
Source File: ActivitiRestClient.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 5
Source File: HttpClientPostingLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
    final CloseableHttpClient client = HttpClients.createDefault();
    final HttpPost httpPost = new HttpPost(SAMPLE_URL);

    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("username", DEFAULT_USER);
    builder.addTextBody("password", DEFAULT_PASS);
    builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
    final HttpEntity multipart = builder.build();

    httpPost.setEntity(multipart);

    final CloseableHttpResponse response = client.execute(httpPost);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
 
Example 6
Source File: RemoteTransformerClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
HttpEntity getRequestEntity(ContentReader reader, String sourceMimetype, String sourceExtension,
                                    String targetExtension, long timeoutMs, String[] args, StringJoiner sj)
{
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    ContentType contentType = ContentType.create(sourceMimetype);
    builder.addBinaryBody("file", reader.getContentInputStream(), contentType, "tmp."+sourceExtension);
    builder.addTextBody("targetExtension", targetExtension);
    sj.add("targetExtension" + '=' + targetExtension);
    for (int i=0; i< args.length; i+=2)
    {
        if (args[i+1] != null)
        {
            builder.addTextBody(args[i], args[i + 1]);

            sj.add(args[i] + '=' + args[i + 1]);
        }
    }

    if (timeoutMs > 0)
    {
        String timeoutMsString = Long.toString(timeoutMs);
        builder.addTextBody("timeout", timeoutMsString);
        sj.add("timeout=" + timeoutMsString);
    }
    return builder.build();
}
 
Example 7
Source File: HttpUtils.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
private MultipartEntityBuilder processBuilderParams(Map<String, Object> params) {
    ContentType contentType = ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    if (params != null) {
        _log.debug(params.toString());
        Object value;
        for (Entry<String, Object> entry : params.entrySet()) {
            value = entry.getValue();
            if (value instanceof File) builder.addBinaryBody(entry.getKey(), (File) value);
            else if (value instanceof CharSequence) {
                builder.addTextBody(entry.getKey(), value.toString(), contentType);
            } else builder.addTextBody(entry.getKey(), JSON.toJSONString(value), contentType);
        }
    }
    return builder;
}
 
Example 8
Source File: EngineRule.java    From camunda-external-task-client-java with Apache License 2.0 6 votes vote down vote up
protected HttpPost createDeploymentRequest(String tenantId, BpmnModelInstance... processes) {
  String uri = String.format(URI_DEPLOYMEN_CREATE, getEngineUrl());
  HttpPost post = new HttpPost(uri);

  MultipartEntityBuilder builder = MultipartEntityBuilder.create()
    .addTextBody("deployment-name", "deployment")
    .addTextBody("enable-duplicate-filtering", "false")
    .addTextBody("deployment-source", "process application");

  if (tenantId != null) {
    builder.addTextBody("tenant-id", tenantId);
  }

  for (int i = 0; i < processes.length; i++) {
    BpmnModelInstance process = processes[i];
    String processAsString = Bpmn.convertToString(process);
    builder.addBinaryBody(
        String.format("data %d", i),
        processAsString.getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_OCTET_STREAM,
        String.format("test%d.bpmn", i));
  }

  HttpEntity entity = builder.build();
  post.setEntity(entity);
  return post;
}
 
Example 9
Source File: HttpClientMultipartLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
    final URL url = Thread.currentThread()
      .getContextClassLoader()
      .getResource("uploads/" + TEXTFILENAME);
    final File file = new File(url.getPath());
    final String message = "This is a multipart post";
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, TEXTFILENAME);
    builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
    final HttpEntity entity = builder.build();
    post.setEntity(entity);
    response = client.execute(post);
    final int statusCode = response.getStatusLine()
      .getStatusCode();
    final String responseString = getContent();
    final String contentTypeInHeader = getContentTypeHeader();
    assertThat(statusCode, equalTo(HttpStatus.SC_OK));
    // assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
    assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
    System.out.println(responseString);
    System.out.println("POST Content Type: " + contentTypeInHeader);
}
 
Example 10
Source File: LineApiImpl.java    From LineAPI4J with MIT License 6 votes vote down vote up
@Override
public void postContent(String url, Map<String, String> data, InputStream is) throws Exception {
  HttpPost httpPost = new HttpPost(url);
  httpPost.addHeader(X_LINE_ACCESS, getAuthToken());
  MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
  for(Map.Entry<String, String> entry : data.entrySet()) {
      entityBuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.APPLICATION_FORM_URLENCODED);
  }
  // The LINE object storage service doesn't support chunked encoding; therefore,
  // we must be able to specify the "Content-Length" header.
  // It can be achieved by giving Apache library either a byte array or a File object.
  entityBuilder.addBinaryBody("file", IOUtils.toByteArray(is));
  httpPost.setEntity(entityBuilder.build());
  HttpResponse response = httpClient.execute(httpPost);
  int statusCode = response.getStatusLine().getStatusCode();
  if (statusCode != HttpStatus.SC_CREATED) {
    throw new IOException("Fail to send request to URL " + url + ". Status: " + statusCode);
  }
}
 
Example 11
Source File: HttpMultipartHelper.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static HttpEntity getMultiPartEntity(String fileName, String contentType, InputStream fileStream, Map<String, String> additionalFormFields) throws IOException {

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

        if (additionalFormFields != null && !additionalFormFields.isEmpty()) {
            for (Entry<String, String> field : additionalFormFields.entrySet()) {
                entityBuilder.addTextBody(field.getKey(), field.getValue());
            }
        }

        entityBuilder.addBinaryBody(fileName, IOUtils.toByteArray(fileStream), ContentType.create(contentType), fileName);

        return entityBuilder.build();
    }
 
Example 12
Source File: RestUtils.java    From slack-api with MIT License 5 votes vote down vote up
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()) {
		if (entry.getValue() != null) {
			multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue());
		}
	}
	return multipartEntityBuilder.build();
}
 
Example 13
Source File: FileSession.java    From timer with Apache License 2.0 5 votes vote down vote up
public Session uploadFile(File file,String filename,String appName,String dirName){

        MultipartEntityBuilder multipartEntity= (MultipartEntityBuilder) this.getProviderService().provider();
        multipartEntity.addBinaryBody("file",file);
        multipartEntity.addTextBody("dirName", dirName);
        multipartEntity.addTextBody("appName",appName);
        multipartEntity.addTextBody("filename",filename);

        return this;
    }
 
Example 14
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 5 votes vote down vote up
private void addInputData(MultipartEntityBuilder builder, InputMedia media, String mediaField, boolean addField) throws JsonProcessingException {
    if (media.isNewMedia()) {
        if (media.getMediaFile() != null) {
            builder.addBinaryBody(media.getMediaName(), media.getMediaFile(), ContentType.APPLICATION_OCTET_STREAM, media.getMediaName());
        } else if (media.getNewMediaStream() != null) {
            builder.addBinaryBody(media.getMediaName(), media.getNewMediaStream(), ContentType.APPLICATION_OCTET_STREAM, media.getMediaName());
        }
    }

    if (media instanceof InputMediaAudio) {
        InputMediaAudio audio = (InputMediaAudio) media;
        if (audio.getThumb() != null) {
            addInputFile(builder, audio.getThumb(), InputMediaAudio.THUMB_FIELD, false);
        }
    } else if (media instanceof InputMediaDocument) {
        InputMediaDocument document = (InputMediaDocument) media;
        if (document.getThumb() != null) {
            addInputFile(builder, document.getThumb(), InputMediaDocument.THUMB_FIELD, false);
        }
    } else if (media instanceof InputMediaVideo) {
        InputMediaVideo video = (InputMediaVideo) media;
        if (video.getThumb() != null) {
            addInputFile(builder, video.getThumb(), InputMediaVideo.THUMB_FIELD, false);
        }
    }

    if (addField) {
        builder.addTextBody(mediaField, objectMapper.writeValueAsString(media), TEXT_PLAIN_CONTENT_TYPE);
    }
}
 
Example 15
Source File: HttpMultipartHelper.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static HttpEntity getMultiPartEntity(String fileName, String contentType, InputStream fileStream, Map<String, String> additionalFormFields) throws IOException {

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

        if (additionalFormFields != null && !additionalFormFields.isEmpty()) {
            for (Entry<String, String> field : additionalFormFields.entrySet()) {
                entityBuilder.addTextBody(field.getKey(), field.getValue());
            }
        }

        entityBuilder.addBinaryBody(fileName, IOUtils.toByteArray(fileStream), ContentType.create(contentType), fileName);

        return entityBuilder.build();
    }
 
Example 16
Source File: AgpClient.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
private HttpEntity createEntity(Map<String, String> params, File file) throws UnsupportedEncodingException {
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  builder.setMode(HttpMultipartMode.RFC6532);
  params.entrySet().stream().forEach(e->builder.addPart(e.getKey(), new StringBody(e.getValue(), ContentType.MULTIPART_FORM_DATA)));
  builder.addBinaryBody("file", file);
  return builder.build();
}
 
Example 17
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void uploadDocument(CloseableHttpClient httpclient) throws IOException {

		System.out.println("uploadDocument(CloseableHttpClient)");
		
		URL url = new URL(BASE_PATH);
		
		HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
        
        AuthCache authCache = new BasicAuthCache();
        authCache.put(targetHost, new BasicScheme());
        
		// Add AuthCache to the execution context
		HttpClientContext context = HttpClientContext.create();
		context.setCredentialsProvider(credsProvider);
		context.setAuthCache(authCache);
		
        HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/document/upload");
       
        File file = new File("c:/users/shatz/Downloads/logicaldocsecurity-171122130133.pdf");
        //File file = new File("C:/tmp/InvoiceProcessing01-workflow.png");  
                
		System.out.println(file.getName());	
		System.out.println(file.getAbsolutePath());	
		
		long folderID = 124358812L;
		
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();         
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		builder.addTextBody("filename", file.getName(), ContentType.TEXT_PLAIN);
		builder.addBinaryBody("filedata", file, ContentType.DEFAULT_BINARY, file.getName());
		builder.addTextBody("folderId", Long.toString(folderID), ContentType.TEXT_PLAIN);		
		
		// 
		HttpEntity entity = builder.build();
		httppost.setEntity(entity);
		
		CloseableHttpResponse response = httpclient.execute(httppost, context);
		
		int code = response.getStatusLine().getStatusCode();
		System.out.println("HTTPstatus code: "+ code);
		
		try {
			HttpEntity rent = response.getEntity();
			if (rent != null) {
				String respoBody = EntityUtils.toString(rent, "UTF-8");
				System.out.println(respoBody);
			}
		} finally {
			response.close();
		}
	}
 
Example 18
Source File: ITStorageSnippets.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@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()));
}
 
Example 19
Source File: HttpUtil.java    From danyuan-application with Apache License 2.0 4 votes vote down vote up
public static String uploadFile(String url, File file) throws ClientProtocolException, IOException {
	CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	CloseableHttpResponse httpResponse = null;
	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
	HttpPost httpPost = new HttpPost(url);
	httpPost.setConfig(requestConfig);
	MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
	// multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));

	// File file = new File("F:\\Ken\\1.PNG");
	// FileBody bin = new FileBody(file);

	// multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
	// 当设置了setSocketTimeout参数后,以下代码上传PDF不能成功,将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
	// multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
	multipartEntityBuilder.addBinaryBody("file", file);
	// multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
	multipartEntityBuilder.addTextBody("comment", "this is comment");
	HttpEntity httpEntity = multipartEntityBuilder.build();
	httpPost.setEntity(httpEntity);

	httpResponse = httpClient.execute(httpPost);
	HttpEntity responseEntity = httpResponse.getEntity();
	int statusCode = httpResponse.getStatusLine().getStatusCode();
	StringBuffer buffer = new StringBuffer();
	if (statusCode == 200) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));

		String str = "";
		while (StringUtils.isNotEmpty(str = reader.readLine())) {
			buffer.append(str);
		}

	}

	httpClient.close();
	if (httpResponse != null) {
		httpResponse.close();
	}
	System.out.println("响应数据:" + buffer.toString());
	return buffer.toString();
}
 
Example 20
Source File: AtsDbLoggerUtilities.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Attach a local file to the a testcase in the Test Explorer DB.
 * <br>The file must not be bigger than 10MB
 * 
 * @param testcaseId the testcase id to which the file will be attached
 * @param fileLocation the absolute path to the file
 * @param testExplorerContextName the name of the web application, e.g. "TestExplorer" or "TestExplorer-4.0.0" etc.
 * @param testExplorerPort the port of the web application, e.g. 8080
 * @return TRUE if the operation was successful and false if not. A warning will be logged on failure.
 */
@PublicAtsApi
public boolean attachFileToTestcase( int testcaseId,
                                     String fileLocation,
                                     String testExplorerContextName,
                                     int testExplorerPort ) {

    fileLocation = fileLocation.replace("\\", "/");
    currentErrMsgPrefix = ERR_MSG_PREFIX.replace("{FILE}", fileLocation).replace("{testcaseID}", testcaseId + "");

    if (!checkFileExist(fileLocation)) {
        return false;
    }
    if (!checkFileSizeIsNotTooLarge(fileLocation)) {
        return false;
    }

    ActiveDbAppender dbAppender = ActiveDbAppender.getCurrentInstance();
    if (dbAppender == null) {
        logger.warn(currentErrMsgPrefix + ". Perhaps the database logging is turned off");
        return false;
    }

    final int runId = dbAppender.getRunId();
    final int suiteId = dbAppender.getSuiteId();

    /* Since the user provides testcase ID, we have to validate it - whether it refers to a testcase part of 
     * the current run and suite
     */
    if (runId < 1 || suiteId < 1 || testcaseId < 1) {
        logger.warn(currentErrMsgPrefix + ". Perhaps the database logging is turned off or you are trying to "
                    + "log while a testcase is not yet started");
        return false;
    }

    final String database = dbAppender.getDatabase();
    final String host = dbAppender.getHost();
    final String URL = "http://" + host + ":" + testExplorerPort + "/" + testExplorerContextName
                       + "/AttachmentsServlet";

    URL url = null;
    try {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        url = post.getURI().toURL();

        if (!isURLConnetionAvailable(url)) {
            return false;
        }
        logger.debug("POSTing " + fileLocation + " to " + URL);

        File file = new File(fileLocation);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, fileLocation);
        builder.addTextBody("dbName", database);
        builder.addTextBody("runId", Integer.toString(runId));
        builder.addTextBody("suiteId", Integer.toString(suiteId));
        builder.addTextBody("testcaseId", Integer.toString(testcaseId));

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        return checkPostExecutedSuccessfully(client.execute(post), fileLocation, testcaseId);
    } catch (FileNotFoundException fnfe) {
        logger.warn(currentErrMsgPrefix + ". It does not exist on the local file system", fnfe);
        return false;
    } catch (IOException ioe) {
        logger.warn(currentErrMsgPrefix + ". Upload to \"" + url + "\" failed", ioe);
        return false;
    }
}