org.apache.http.entity.mime.MultipartEntityBuilder#build ( )源码实例Demo

下面列出了org.apache.http.entity.mime.MultipartEntityBuilder#build ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ATest   文件: HttpClientUtil.java
/**
 * 发送 post请求(带文件)
 * 
 * @param httpUrl
 *            地址
 * @param maps
 *            参数
 * @param fileLists
 *            附件
 */
public ResponseContent sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists,
		Map<String, String> headers, RequestConfig requestConfig, int executionCount, int retryInterval) {
	HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
	MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
	if (null != maps && maps.size() > 0) {
		for (String key : maps.keySet()) {
			meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
		}
	}
	for (File file : fileLists) {
		FileBody fileBody = new FileBody(file);
		meBuilder.addPart("files", fileBody);
	}
	HttpEntity reqEntity = meBuilder.build();
	httpPost.setEntity(reqEntity);
	return sendHttpPost(httpPost, headers, requestConfig, executionCount, retryInterval);
}
 
源代码2 项目: tutorials   文件: HttpClientMultipartLiveTest.java
@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);
}
 
源代码3 项目: archivo   文件: CrashReportTask.java
private void performUpload() {
    Path gzLog = compressLog();
    try (CloseableHttpClient client = buildHttpClient()) {
        HttpPost post = new HttpPost(CRASH_REPORT_URL);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody logFile = new FileBody(gzLog.toFile(), ContentType.DEFAULT_BINARY);
        builder.addPart("log", logFile);
        StringBody uid = new StringBody(userId, ContentType.TEXT_PLAIN);
        builder.addPart("uid", uid);
        HttpEntity postEntity = builder.build();
        post.setEntity(postEntity);
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            logger.debug("Error uploading crash report: {}", response.getStatusLine());
        }
    } catch (IOException e) {
        logger.error("Error uploading crash report: {}", e.getLocalizedMessage());
    }
}
 
源代码4 项目: AthenaServing   文件: HttpClientUtil.java
/**
 * 发送post请求(带文件)
 *
 * @param url
 * @param maps
 * @param fileLists
 * @return
 */
public String sendHttpPost(String url, Map<String, String> maps, List<File> fileLists) {
    HttpPost httpPost = new HttpPost(url);
    MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
    for (String key : maps.keySet()) {
        meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
    }
    for (File file : fileLists) {
        FileBody fileBody = new FileBody(file);
        meBuilder.addPart("files", fileBody);
    }
    HttpEntity reqEntity = meBuilder.build();
    httpPost.setEntity(reqEntity);
    return this.sendHttpPost(httpPost);
}
 
源代码5 项目: activiti6-boot2   文件: HttpMultipartHelper.java
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();
  }
 
private static HttpUriRequest getUploadSegmentMetadataFilesRequest(URI uri, Map<String, File> metadataFiles,
    int segmentUploadRequestTimeoutMs) {
  MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().
      setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  for (Map.Entry<String, File> entry : metadataFiles.entrySet()) {
    multipartEntityBuilder.addPart(entry.getKey(), getContentBody(entry.getKey(), entry.getValue()));
  }
  HttpEntity entity = multipartEntityBuilder.build();

  // Build the POST request.
  RequestBuilder requestBuilder =
      RequestBuilder.create(HttpPost.METHOD_NAME).setVersion(HttpVersion.HTTP_1_1).setUri(uri).setEntity(entity);
  setTimeout(requestBuilder, segmentUploadRequestTimeoutMs);
  return requestBuilder.build();
}
 
源代码7 项目: sendcloud4j   文件: MailWebApi.java
private HttpEntity getMultipartEmailHttpEntity(Email email) {
    MultipartEntityBuilder entityBuilder = createEntityBuilder();

    Map<String, byte[]> attachments = email.attachments();
    for (Map.Entry<String, byte[]> attachment : attachments.entrySet()) {
        entityBuilder.addBinaryBody(email.attachmentsKey(), attachment.getValue(),
                ContentType.MULTIPART_FORM_DATA, attachment.getKey());
    }
    addParametersToTextBody(entityBuilder, email.getParameters());

    return entityBuilder.build();
}
 
源代码8 项目: blynk-server   文件: OTATest.java
@Test
public void basicOTAForSingleUserAndNonExistingProject() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?user=" + getUserName() + "&project=123");
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    TestHardClient newHardwareClient = new TestHardClient("localhost", properties.getHttpPort());
    newHardwareClient.start();
    newHardwareClient.login(clientPair.token);
    verify(newHardwareClient.responseMock, timeout(1000)).channelRead(any(), eq(ok(1)));
    newHardwareClient.reset();

    newHardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
    verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1)));
    verify(clientPair.hardwareClient.responseMock, never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
}
 
源代码9 项目: flowable-engine   文件: HttpMultipartHelper.java
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();
    }
 
源代码10 项目: swagger-aem   文件: CrxApi.java
/**
 * 
 * 

*/
public void getCrxdeStatus (final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
  Object postBody = null;


  // create path and map variables
  String path = "/crx/server/crx.default/jcr:root/.1.json".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  // header params
  Map<String, String> headerParams = new HashMap<String, String>();
  // form params
  Map<String, String> formParams = new HashMap<String, String>();



  String[] contentTypes = {
    
  };
  String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

  if (contentType.startsWith("multipart/form-data")) {
    // file uploading
    MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
    

    HttpEntity httpEntity = localVarBuilder.build();
    postBody = httpEntity;
  } else {
    // normal form params
        }

  String[] authNames = new String[] { "aemAuth" };

  try {
    apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
      new Response.Listener<String>() {
        @Override
        public void onResponse(String localVarResponse) {
          try {
            responseListener.onResponse((String) ApiInvoker.deserialize(localVarResponse,  "", String.class));
          } catch (ApiException exception) {
             errorListener.onErrorResponse(new VolleyError(exception));
          }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
          errorListener.onErrorResponse(error);
        }
    });
  } catch (ApiException ex) {
    errorListener.onErrorResponse(new VolleyError(ex));
  }
}
 
源代码11 项目: TelegramBots   文件: DefaultAbsSender.java
@Override
public final Message execute(SendDocument sendDocument) throws TelegramApiException {
    assertParamNotNull(sendDocument, "sendDocument");

    sendDocument.validate();
    try {
        String url = getBaseUrl() + SendDocument.PATH;
        HttpPost httppost = configuredHttpPost(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId(), TEXT_PLAIN_CONTENT_TYPE);

        addInputFile(builder, sendDocument.getDocument(), SendDocument.DOCUMENT_FIELD, true);

        if (sendDocument.getReplyMarkup() != null) {
            builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendDocument.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendDocument.getReplyToMessageId() != null) {
            builder.addTextBody(SendDocument.REPLYTOMESSAGEID_FIELD, sendDocument.getReplyToMessageId().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendDocument.getCaption() != null) {
            builder.addTextBody(SendDocument.CAPTION_FIELD, sendDocument.getCaption(), TEXT_PLAIN_CONTENT_TYPE);
            if (sendDocument.getParseMode() != null) {
                builder.addTextBody(SendDocument.PARSEMODE_FIELD, sendDocument.getParseMode(), TEXT_PLAIN_CONTENT_TYPE);
            }
        }
        if (sendDocument.getDisableNotification() != null) {
            builder.addTextBody(SendDocument.DISABLENOTIFICATION_FIELD, sendDocument.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }

        if (sendDocument.getThumb() != null) {
            addInputFile(builder, sendDocument.getThumb(), SendDocument.THUMB_FIELD, false);
            builder.addTextBody(SendDocument.THUMB_FIELD, sendDocument.getThumb().getAttachName(), TEXT_PLAIN_CONTENT_TYPE);
        }

        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);

        return sendDocument.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to send document", e);
    }
}
 
源代码12 项目: blynk-server   文件: OTATest.java
@Test
public void testImprovedUploadMethodAndCheckOTAStatusForDeviceThatWasOnline() throws Exception {
    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 fm 0.3.3 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
    clientPair.hardwareClient.verifyResult(ok(1));

    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    String path;
    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        path = TestUtil.consumeText(response);

        assertNotNull(path);
        assertTrue(path.startsWith("/static"));
        assertTrue(path.endsWith("bin"));
    }

    String responseUrl = "http://127.0.0.1:18080" + path;
    verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));

    clientPair.appClient.getDevice(1, 0);
    Device device = clientPair.appClient.parseDevice(1);

    assertNotNull(device);

    assertEquals("0.3.1", device.hardwareInfo.blynkVersion);
    assertEquals(10, device.hardwareInfo.heartbeatInterval);
    assertEquals("111", device.hardwareInfo.build);
    assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaUpdateAt, 5000);

    clientPair.hardwareClient.send("internal " + b("ver 0.3.1 fm 0.3.3 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 112"));
    clientPair.hardwareClient.verifyResult(ok(2));

    clientPair.appClient.getDevice(1, 0);
    device = clientPair.appClient.parseDevice(2);

    assertNotNull(device);

    assertEquals("0.3.1", device.hardwareInfo.blynkVersion);
    assertEquals(10, device.hardwareInfo.heartbeatInterval);
    assertEquals("112", device.hardwareInfo.build);
    assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000);
    assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaUpdateAt, 5000);
}
 
源代码13 项目: swagger-aem   文件: SlingApi.java
/**
 * 
 * 
 * @param proxyHost    * @param proxyHostTypeHint    * @param proxyPort    * @param proxyPortTypeHint    * @param proxyExceptions    * @param proxyExceptionsTypeHint    * @param proxyEnabled    * @param proxyEnabledTypeHint    * @param proxyUser    * @param proxyUserTypeHint    * @param proxyPassword    * @param proxyPasswordTypeHint 
*/
public void postConfigApacheHttpComponentsProxyConfiguration (String proxyHost, String proxyHostTypeHint, Integer proxyPort, String proxyPortTypeHint, List<String> proxyExceptions, String proxyExceptionsTypeHint, Boolean proxyEnabled, String proxyEnabledTypeHint, String proxyUser, String proxyUserTypeHint, String proxyPassword, String proxyPasswordTypeHint, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
  Object postBody = null;


  // create path and map variables
  String path = "/apps/system/config/org.apache.http.proxyconfigurator.config".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  // header params
  Map<String, String> headerParams = new HashMap<String, String>();
  // form params
  Map<String, String> formParams = new HashMap<String, String>();

  queryParams.addAll(ApiInvoker.parameterToPairs("", "proxy.host", proxyHost));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "[email protected]", proxyHostTypeHint));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "proxy.port", proxyPort));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "[email protected]", proxyPortTypeHint));
  queryParams.addAll(ApiInvoker.parameterToPairs("multi", "proxy.exceptions", proxyExceptions));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "[email protected]", proxyExceptionsTypeHint));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "proxy.enabled", proxyEnabled));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "[email protected]", proxyEnabledTypeHint));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "proxy.user", proxyUser));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "[email protected]", proxyUserTypeHint));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "proxy.password", proxyPassword));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "[email protected]", proxyPasswordTypeHint));


  String[] contentTypes = {
    
  };
  String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

  if (contentType.startsWith("multipart/form-data")) {
    // file uploading
    MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
    

    HttpEntity httpEntity = localVarBuilder.build();
    postBody = httpEntity;
  } else {
    // normal form params
        }

  String[] authNames = new String[] { "aemAuth" };

  try {
    apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames,
      new Response.Listener<String>() {
        @Override
        public void onResponse(String localVarResponse) {
            responseListener.onResponse(localVarResponse);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
          errorListener.onErrorResponse(error);
        }
    });
  } catch (ApiException ex) {
    errorListener.onErrorResponse(new VolleyError(ex));
  }
}
 
源代码14 项目: swaggy-jenkins   文件: BaseRemoteAccessApi.java
/**
 * 
 * Retrieve CSRF protection token

*/
public void getCrumb (final Response.Listener<DefaultCrumbIssuer> responseListener, final Response.ErrorListener errorListener) {
  Object postBody = null;


  // create path and map variables
  String path = "/crumbIssuer/api/json".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  // header params
  Map<String, String> headerParams = new HashMap<String, String>();
  // form params
  Map<String, String> formParams = new HashMap<String, String>();



  String[] contentTypes = {
    
  };
  String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

  if (contentType.startsWith("multipart/form-data")) {
    // file uploading
    MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
    

    HttpEntity httpEntity = localVarBuilder.build();
    postBody = httpEntity;
  } else {
    // normal form params
        }

  String[] authNames = new String[] { "jenkins_auth" };

  try {
    apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
      new Response.Listener<String>() {
        @Override
        public void onResponse(String localVarResponse) {
          try {
            responseListener.onResponse((DefaultCrumbIssuer) ApiInvoker.deserialize(localVarResponse,  "", DefaultCrumbIssuer.class));
          } catch (ApiException exception) {
             errorListener.onErrorResponse(new VolleyError(exception));
          }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
          errorListener.onErrorResponse(error);
        }
    });
  } catch (ApiException ex) {
    errorListener.onErrorResponse(new VolleyError(ex));
  }
}
 
源代码15 项目: openapi-generator   文件: UserApi.java
/**
 * Creates list of users with given input array
 * 
 * @param user List of user object
 * @return void
 */
public void  createUsersWithListInput (List<User> user) throws ApiException {
  Object localVarPostBody = user;
  // verify the required parameter 'user' is set
  if (user == null) {
     throw new ApiException(400, "Missing the required parameter 'user' when calling createUsersWithListInput");
  }

  // create path and map variables
  String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> localVarQueryParams = new ArrayList<Pair>();
  // header params
  Map<String, String> localVarHeaderParams = new HashMap<String, String>();
  // form params
  Map<String, String> localVarFormParams = new HashMap<String, String>();



  String[] localVarContentTypes = {
    
  };
  String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json";

  if (localVarContentType.startsWith("multipart/form-data")) {
    // file uploading
    MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
    

    localVarPostBody = localVarBuilder.build();
  } else {
    // normal form params
        }

  try {
    String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType);
    if(localVarResponse != null){
      return ;
    }
    else {
      return ;
    }
  } catch (ApiException ex) {
    throw ex;
  }
}
 
源代码16 项目: swaggy-jenkins   文件: RemoteAccessApi.java
/**
 * 
 * Retrieve queue details

*/
public void getQueue (final Response.Listener<Queue> responseListener, final Response.ErrorListener errorListener) {
  Object postBody = null;


  // create path and map variables
  String path = "/queue/api/json".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  // header params
  Map<String, String> headerParams = new HashMap<String, String>();
  // form params
  Map<String, String> formParams = new HashMap<String, String>();



  String[] contentTypes = {
    
  };
  String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

  if (contentType.startsWith("multipart/form-data")) {
    // file uploading
    MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
    

    HttpEntity httpEntity = localVarBuilder.build();
    postBody = httpEntity;
  } else {
    // normal form params
        }

  String[] authNames = new String[] { "jenkins_auth" };

  try {
    apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
      new Response.Listener<String>() {
        @Override
        public void onResponse(String localVarResponse) {
          try {
            responseListener.onResponse((Queue) ApiInvoker.deserialize(localVarResponse,  "", Queue.class));
          } catch (ApiException exception) {
             errorListener.onErrorResponse(new VolleyError(exception));
          }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
          errorListener.onErrorResponse(error);
        }
    });
  } catch (ApiException ex) {
    errorListener.onErrorResponse(new VolleyError(ex));
  }
}
 
源代码17 项目: nifi   文件: PostSlack.java
private HttpEntity createFileMessageRequestBody(ProcessContext context, ProcessSession session, FlowFile flowFile) throws PostSlackException {
    MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();

    String channel = context.getProperty(CHANNEL).evaluateAttributeExpressions(flowFile).getValue();
    if (channel == null || channel.isEmpty()) {
        throw new PostSlackException("The channel must be specified.");
    }
    multipartBuilder.addTextBody("channels", channel, MIME_TYPE_PLAINTEXT_UTF8);

    String text = context.getProperty(TEXT).evaluateAttributeExpressions(flowFile).getValue();
    if (text != null && !text.isEmpty()) {
        multipartBuilder.addTextBody("initial_comment", text, MIME_TYPE_PLAINTEXT_UTF8);
    }

    String title = context.getProperty(FILE_TITLE).evaluateAttributeExpressions(flowFile).getValue();
    if (title != null && !title.isEmpty()) {
        multipartBuilder.addTextBody("title", title, MIME_TYPE_PLAINTEXT_UTF8);
    }

    String fileName = context.getProperty(FILE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    if (fileName == null || fileName.isEmpty()) {
        fileName = "file";
        getLogger().warn("File name not specified, has been set to {}.", new Object[]{ fileName });
    }
    multipartBuilder.addTextBody("filename", fileName, MIME_TYPE_PLAINTEXT_UTF8);

    ContentType mimeType;
    String mimeTypeStr = context.getProperty(FILE_MIME_TYPE).evaluateAttributeExpressions(flowFile).getValue();
    if (mimeTypeStr == null || mimeTypeStr.isEmpty()) {
        mimeType = ContentType.APPLICATION_OCTET_STREAM;
        getLogger().warn("Mime type not specified, has been set to {}.", new Object[]{ mimeType.getMimeType() });
    } else {
        mimeType = ContentType.getByMimeType(mimeTypeStr);
        if (mimeType == null) {
            mimeType = ContentType.APPLICATION_OCTET_STREAM;
            getLogger().warn("Unknown mime type specified ({}), has been set to {}.", new Object[]{ mimeTypeStr, mimeType.getMimeType() });
        }
    }

    multipartBuilder.addBinaryBody("file", session.read(flowFile), mimeType, fileName);

    return multipartBuilder.build();
}
 
源代码18 项目: swagger-aem   文件: SlingApi.java
/**
 * 
 * 
 * @param alias    * @param aliasTypeHint    * @param davCreateAbsoluteUri    * @param davCreateAbsoluteUriTypeHint 
*/
public void postConfigApacheSlingDavExServlet (String alias, String aliasTypeHint, Boolean davCreateAbsoluteUri, String davCreateAbsoluteUriTypeHint, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
  Object postBody = null;


  // create path and map variables
  String path = "/apps/system/config/org.apache.sling.jcr.davex.impl.servlets.SlingDavExServlet".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  // header params
  Map<String, String> headerParams = new HashMap<String, String>();
  // form params
  Map<String, String> formParams = new HashMap<String, String>();

  queryParams.addAll(ApiInvoker.parameterToPairs("", "alias", alias));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "[email protected]", aliasTypeHint));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "dav.create-absolute-uri", davCreateAbsoluteUri));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "[email protected]", davCreateAbsoluteUriTypeHint));


  String[] contentTypes = {
    
  };
  String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

  if (contentType.startsWith("multipart/form-data")) {
    // file uploading
    MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
    

    HttpEntity httpEntity = localVarBuilder.build();
    postBody = httpEntity;
  } else {
    // normal form params
        }

  String[] authNames = new String[] { "aemAuth" };

  try {
    apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames,
      new Response.Listener<String>() {
        @Override
        public void onResponse(String localVarResponse) {
            responseListener.onResponse(localVarResponse);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
          errorListener.onErrorResponse(error);
        }
    });
  } catch (ApiException ex) {
    errorListener.onErrorResponse(new VolleyError(ex));
  }
}
 
源代码19 项目: TelegramBots   文件: DefaultAbsSender.java
/**
 * Sends a file using Send Audio method (https://core.telegram.org/bots/api#sendaudio)
 * @param sendAudio Information to send
 * @return If success, the sent Message is returned
 * @throws TelegramApiException If there is any error sending the audio
 */
@Override
public final Message execute(SendAudio sendAudio) throws TelegramApiException {
    assertParamNotNull(sendAudio, "sendAudio");
    sendAudio.validate();
    try {
        String url = getBaseUrl() + SendAudio.PATH;
        HttpPost httppost = configuredHttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody(SendAudio.CHATID_FIELD, sendAudio.getChatId(), TEXT_PLAIN_CONTENT_TYPE);
        addInputFile(builder, sendAudio.getAudio(), SendAudio.AUDIO_FIELD, true);

        if (sendAudio.getReplyMarkup() != null) {
            builder.addTextBody(SendAudio.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendAudio.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendAudio.getReplyToMessageId() != null) {
            builder.addTextBody(SendAudio.REPLYTOMESSAGEID_FIELD, sendAudio.getReplyToMessageId().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendAudio.getPerformer() != null) {
            builder.addTextBody(SendAudio.PERFOMER_FIELD, sendAudio.getPerformer(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendAudio.getTitle() != null) {
            builder.addTextBody(SendAudio.TITLE_FIELD, sendAudio.getTitle(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if(sendAudio.getDuration() != null){
            builder.addTextBody(SendAudio.DURATION_FIELD, sendAudio.getDuration().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendAudio.getDisableNotification() != null) {
            builder.addTextBody(SendAudio.DISABLENOTIFICATION_FIELD, sendAudio.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendAudio.getCaption() != null) {
            builder.addTextBody(SendAudio.CAPTION_FIELD, sendAudio.getCaption(), TEXT_PLAIN_CONTENT_TYPE);
            if (sendAudio.getParseMode() != null) {
                builder.addTextBody(SendAudio.PARSEMODE_FIELD, sendAudio.getParseMode(), TEXT_PLAIN_CONTENT_TYPE);
            }
        }
        if (sendAudio.getThumb() != null) {
            addInputFile(builder, sendAudio.getThumb(), SendAudio.THUMB_FIELD, false);
            builder.addTextBody(SendAudio.THUMB_FIELD, sendAudio.getThumb().getAttachName(), TEXT_PLAIN_CONTENT_TYPE);
        }

        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);


        return sendAudio.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to send audio", e);
    }
}
 
源代码20 项目: swagger-aem   文件: SlingApi.java
/**
 * 
 * 
 * @param operation    * @param newPassword    * @param rePassword    * @param keyStoreType    * @param removeAlias    * @param certificate 
*/
public void postTruststore (String operation, String newPassword, String rePassword, String keyStoreType, String removeAlias, File certificate, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
  Object postBody = null;


  // create path and map variables
  String path = "/libs/granite/security/post/truststore".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  // header params
  Map<String, String> headerParams = new HashMap<String, String>();
  // form params
  Map<String, String> formParams = new HashMap<String, String>();

  queryParams.addAll(ApiInvoker.parameterToPairs("", ":operation", operation));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "newPassword", newPassword));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "rePassword", rePassword));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "keyStoreType", keyStoreType));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "removeAlias", removeAlias));


  String[] contentTypes = {
    "multipart/form-data"
  };
  String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

  if (contentType.startsWith("multipart/form-data")) {
    // file uploading
    MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
    
    if (certificate != null) {
      localVarBuilder.addBinaryBody("certificate", certificate);
    }
    

    HttpEntity httpEntity = localVarBuilder.build();
    postBody = httpEntity;
  } else {
    // normal form params
    
  }

  String[] authNames = new String[] { "aemAuth" };

  try {
    apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames,
      new Response.Listener<String>() {
        @Override
        public void onResponse(String localVarResponse) {
          try {
            responseListener.onResponse((String) ApiInvoker.deserialize(localVarResponse,  "", String.class));
          } catch (ApiException exception) {
             errorListener.onErrorResponse(new VolleyError(exception));
          }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
          errorListener.onErrorResponse(error);
        }
    });
  } catch (ApiException ex) {
    errorListener.onErrorResponse(new VolleyError(ex));
  }
}