List of usage examples for org.apache.http.entity ContentType create
public static ContentType create(String str, String str2) throws UnsupportedCharsetException
From source file:org.apache.hadoop.gateway.GatewayFuncTestDriver.java
public String oozieSubmitJob(String user, String password, String request, int status) throws IOException, URISyntaxException { getMock("OOZIE").expect().method("POST").pathInfo("/v1/jobs").respond().status(HttpStatus.SC_CREATED) .content(getResourceBytes("oozie-jobs-submit-response.json")).contentType("application/json"); //System.out.println( "REQUEST LENGTH = " + request.length() ); URL url = new URL(getUrl("OOZIE") + "/v1/jobs?action=start" + (isUseGateway() ? "" : "&user.name=" + user)); HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(user, password)); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpPost post = new HttpPost(url.toURI()); // post.getParams().setParameter( "action", "start" ); StringEntity entity = new StringEntity(request, ContentType.create("application/xml", "UTF-8")); post.setEntity(entity);//from w w w . j a va 2 s .co m post.setHeader("X-XSRF-Header", "ksdjfhdsjkfhds"); HttpResponse response = client.execute(targetHost, post, localContext); assertThat(response.getStatusLine().getStatusCode(), is(status)); String json = EntityUtils.toString(response.getEntity()); // String json = given() // .log().all() // .auth().preemptive().basic( user, password ) // .queryParam( "action", "start" ) // .contentType( "application/xml;charset=UTF-8" ) // .content( request ) // .expect() // .log().all() // .statusCode( status ) // .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString(); //System.out.println( "JSON=" + json ); String id = from(json).getString("id"); return id; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java
/** * //ww w .ja va 2 s . c o m * @param post {@link HttpPost} * @return String posted body if computable * @throws IOException if sending the data fails due to I/O */ protected String sendPostData(HttpPost post) throws IOException { // Buffer to hold the post body, except file content StringBuilder postedBody = new StringBuilder(1000); HTTPFileArg[] files = getHTTPFiles(); final String contentEncoding = getContentEncodingOrNull(); final boolean haveContentEncoding = contentEncoding != null; // Check if we should do a multipart/form-data or an // application/x-www-form-urlencoded post request if (getUseMultipartForPost()) { // If a content encoding is specified, we use that as the // encoding of any parameter values Charset charset = null; if (haveContentEncoding) { charset = Charset.forName(contentEncoding); } else { charset = MIME.DEFAULT_CHARSET; } if (log.isDebugEnabled()) { log.debug("Building multipart with:getDoBrowserCompatibleMultipart():" + getDoBrowserCompatibleMultipart() + ", with charset:" + charset + ", haveContentEncoding:" + haveContentEncoding); } // Write the request to our own stream MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset); if (getDoBrowserCompatibleMultipart()) { multipartEntityBuilder.setLaxMode(); } else { multipartEntityBuilder.setStrictMode(); } // Create the parts // Add any parameters for (JMeterProperty jMeterProperty : getArguments()) { HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue(); String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } StringBody stringBody = new StringBody(arg.getValue(), ContentType.create("text/plain", charset)); FormBodyPart formPart = FormBodyPartBuilder.create(parameterName, stringBody).build(); multipartEntityBuilder.addPart(formPart); } // Add any files // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here. ViewableFileBody[] fileBodies = new ViewableFileBody[files.length]; for (int i = 0; i < files.length; i++) { HTTPFileArg file = files[i]; File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath()); fileBodies[i] = new ViewableFileBody(reservedFile, file.getMimeType()); multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]); } HttpEntity entity = multipartEntityBuilder.build(); post.setEntity(entity); if (entity.isRepeatable()) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ViewableFileBody fileBody : fileBodies) { fileBody.hideFileData = true; } entity.writeTo(bos); for (ViewableFileBody fileBody : fileBodies) { fileBody.hideFileData = false; } bos.flush(); // We get the posted bytes using the encoding used to create it postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient : contentEncoding)); bos.close(); } else { postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$ } // // Set the content type TODO - needed? // String multiPartContentType = multiPart.getContentType().getValue(); // post.setHeader(HEADER_CONTENT_TYPE, multiPartContentType); } else { // not multipart // Check if the header manager had a content type header // This allows the user to specify his own content-type for a POST request Header contentTypeHeader = post.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE); boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0; // If there are no arguments, we can send a file as the body of the request // TODO: needs a multiple file upload scenerio if (!hasArguments() && getSendFileAsPostBody()) { // If getSendFileAsPostBody returned true, it's sure that file is not null HTTPFileArg file = files[0]; if (!hasContentTypeHeader) { // Allow the mimetype of the file to control the content type if (file.getMimeType() != null && file.getMimeType().length() > 0) { post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType()); } else { post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED); } } FileEntity fileRequestEntity = new FileEntity(new File(file.getPath()), (ContentType) null);// TODO is null correct? post.setEntity(fileRequestEntity); // We just add placeholder text for file content postedBody.append("<actual file content, not shown here>"); } else { // In a post request which is not multipart, we only support // parameters, no file upload is allowed // If a content encoding is specified, we set it as http parameter, so that // the post body will be encoded in the specified content encoding if (haveContentEncoding) { post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, contentEncoding); } // If none of the arguments have a name specified, we // just send all the values as the post body if (getSendParameterValuesAsPostBody()) { // Allow the mimetype of the file to control the content type // This is not obvious in GUI if you are not uploading any files, // but just sending the content of nameless parameters // TODO: needs a multiple file upload scenerio if (!hasContentTypeHeader) { HTTPFileArg file = files.length > 0 ? files[0] : null; if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) { post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType()); } else { // TODO - is this the correct default? post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED); } } // Just append all the parameter values, and use that as the post body StringBuilder postBody = new StringBuilder(); for (JMeterProperty jMeterProperty : getArguments()) { HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue(); // Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue if (haveContentEncoding) { postBody.append(arg.getEncodedValue(contentEncoding)); } else { postBody.append(arg.getEncodedValue()); } } // Let StringEntity perform the encoding StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding); post.setEntity(requestEntity); postedBody.append(postBody.toString()); } else { // It is a normal post request, with parameter names and values // Set the content type if (!hasContentTypeHeader) { post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED); } // Add the parameters PropertyIterator args = getArguments().iterator(); List<NameValuePair> nvps = new ArrayList<>(); String urlContentEncoding = contentEncoding; if (urlContentEncoding == null || urlContentEncoding.length() == 0) { // Use the default encoding for urls urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING; } while (args.hasNext()) { HTTPArgument arg = (HTTPArgument) args.next().getObjectValue(); // The HTTPClient always urlencodes both name and value, // so if the argument is already encoded, we have to decode // it before adding it to the post request String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } String parameterValue = arg.getValue(); if (!arg.isAlwaysEncoded()) { // The value is already encoded by the user // Must decode the value now, so that when the // httpclient encodes it, we end up with the same value // as the user had entered. parameterName = URLDecoder.decode(parameterName, urlContentEncoding); parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding); } // Add the parameter, httpclient will urlencode it nvps.add(new BasicNameValuePair(parameterName, parameterValue)); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, urlContentEncoding); post.setEntity(entity); if (entity.isRepeatable()) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); post.getEntity().writeTo(bos); bos.flush(); // We get the posted bytes using the encoding used to create it if (contentEncoding != null) { postedBody.append(new String(bos.toByteArray(), contentEncoding)); } else { postedBody.append(new String(bos.toByteArray(), SampleResult.DEFAULT_HTTP_ENCODING)); } bos.close(); } else { postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>"); } } } } return postedBody.toString(); }
From source file:org.eclipse.californium.proxy.HttpTranslator.java
/** * Generates an HTTP entity starting from a CoAP request. If the coap * message has no payload, it returns a null http entity. It takes the * payload from the CoAP message and encapsulates it in an entity. If the * content-type is recognized, and a mapping is present in the properties * file, it is translated to the correspondent in HTTP, otherwise it is set * to application/octet-stream. If the content-type has a charset, namely it * is printable, the payload is encapsulated in a StringEntity, if not it a * ByteArrayEntity is used.// w w w. ja va 2 s . co m * * * @param coapMessage * the coap message * * * @return null if the request has no payload * @throws TranslationException * the translation exception */ public static HttpEntity getHttpEntity(Message coapMessage) throws TranslationException { if (coapMessage == null) { throw new IllegalArgumentException("coapMessage == null"); } // the result HttpEntity httpEntity = null; // check if coap request has a payload byte[] payload = coapMessage.getPayload(); if (payload != null && payload.length != 0) { ContentType contentType = null; // if the content type is not set, translate with octect-stream if (!coapMessage.getOptions().hasContentFormat()) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { int coapContentType = coapMessage.getOptions().getContentFormat(); // search for the media type inside the property file String coapContentTypeString = HTTP_TRANSLATION_PROPERTIES .getProperty(KEY_COAP_MEDIA + coapContentType); // if the content-type has not been found in the property file, // try to get its string value (expressed in mime type) if (coapContentTypeString == null || coapContentTypeString.isEmpty()) { coapContentTypeString = MediaTypeRegistry.toString(coapContentType); // if the coap content-type is printable, it is needed to // set the default charset (i.e., UTF-8) if (MediaTypeRegistry.isPrintable(coapContentType)) { coapContentTypeString += "; charset=UTF-8"; } } // parse the content type try { contentType = ContentType.parse(coapContentTypeString); } catch (UnsupportedCharsetException e) { LOGGER.finer("Cannot convert string to ContentType: " + e.getMessage()); contentType = ContentType.APPLICATION_OCTET_STREAM; } } // get the charset Charset charset = contentType.getCharset(); // if there is a charset, means that the content is not binary if (charset != null) { String body = ""; try { body = new String(payload, "UTF-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } body = body.replace("coap://", "http://" + proxyIP + ":8080/proxy/"); payload = body.getBytes(); // according to the class ContentType the default content-type // with UTF-8 charset is application/json. If the content-type // parsed is different and is not iso encoded, a translation is // needed Charset isoCharset = ISO_8859_1; /*if (!charset.equals(isoCharset) && !contentType.getMimeType().equals(ContentType.APPLICATION_JSON.getMimeType())) { byte[] newPayload = changeCharset(payload, charset, isoCharset); // since ISO-8859-1 is a subset of UTF-8, it is needed to // check if the mapping could be accomplished, only if the // operation is succesful the payload and the charset should // be changed if (newPayload != null) { payload = newPayload; // if the charset is changed, also the entire // content-type must change contentType = ContentType.create(contentType.getMimeType(), isoCharset); } }*/ // create the content String payloadString = new String(payload, contentType.getCharset()); // create the entity httpEntity = new StringEntity(payloadString, ContentType.create(contentType.getMimeType(), contentType.getCharset())); } else { // create the entity httpEntity = new ByteArrayEntity(payload); } // set the content-type ((AbstractHttpEntity) httpEntity).setContentType(contentType.getMimeType()); } return httpEntity; }
From source file:org.mule.modules.wechat.common.HttpsConnection.java
public Map<String, Object> postFile(String httpsURL, String title, String introduction, DataHandler attachment) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(httpsURL); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Get extension of attachment TikaConfig config = TikaConfig.getDefaultConfig(); MimeTypes allTypes = config.getMimeRepository(); String ext = allTypes.forName(attachment.getContentType()).getExtension(); if (ext.equals("")) { ContentTypeEnum contentTypeEnum = ContentTypeEnum .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase()); ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse(""); }// www . j av a 2 s . c o m // Create file InputStream fis = attachment.getInputStream(); byte[] bytes = IOUtils.toByteArray(fis); File f = new File(System.getProperty("user.dir") + "/fileTemp/" + title + ext); FileUtils.writeByteArrayToFile(f, bytes); // Create JSON JSONObject obj = new JSONObject(); obj.put("title", title); obj.put("introduction", introduction); ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8")); builder.addBinaryBody("media", f); builder.addTextBody("description", obj.toString(), contentType); // Post to wechat HttpEntity entity = builder.build(); post.setEntity(entity); CloseableHttpResponse httpResponse = httpClient.execute(post); String content = ""; try { HttpEntity _entity = httpResponse.getEntity(); content = EntityUtils.toString(_entity); EntityUtils.consume(_entity); } finally { httpResponse.close(); } f.delete(); // Convert JSON string to Map ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() { }); return map; }
From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java
/** * * @param soapActionHeader// w ww. j ava 2 s.c om * String in HTTP Header. specific for each TR064 service * @param request * the SOAPMEssage Object to send to fbox as request * @param serviceUrl * URL to sent the SOAP Message to (service specific) * @return */ private SOAPMessage readSoapResponse(String soapActionHeader, SOAPMessage request, String serviceUrl) { SOAPMessage response = null; // Soap Body to post HttpPost postSoap = new HttpPost(serviceUrl); // url is service specific postSoap.addHeader("SOAPAction", soapActionHeader); // add the Header specific for this request HttpEntity entBody = null; HttpResponse resp = null; // stores raw response from fbox boolean exceptionOccurred = false; try { entBody = new StringEntity(soapToString(request), ContentType.create("text/xml", "UTF-8")); // add body postSoap.setEntity(entBody); synchronized (_httpClient) { resp = _httpClient.execute(postSoap, _httpClientContext); } // Fetch content data StatusLine slResponse = resp.getStatusLine(); HttpEntity heResponse = resp.getEntity(); // Check for (auth-) error if (slResponse.getStatusCode() == 401) { logger.warn( "Could not read response from FritzBox. Unauthorized! Check user and password in config. " + "Verify configured user for tr064 requests. Reason from Fritzbox was: {}", slResponse.getReasonPhrase()); postSoap.releaseConnection(); resetHttpClient(); return null; } // Parse response into SOAP Message response = MessageFactory.newInstance().createMessage(null, heResponse.getContent()); } catch (UnsupportedEncodingException e) { logger.error("Encoding not supported: {}", e.getMessage().toString()); exceptionOccurred = true; } catch (ClientProtocolException e) { logger.error("Client Protocol not supported: {}", e.getMessage().toString()); exceptionOccurred = true; } catch (IOException e) { logger.error("Cannot send/receive: {}", e.getMessage().toString()); exceptionOccurred = true; } catch (UnsupportedOperationException e) { logger.error("Operation unsupported: {}", e.getMessage().toString()); response = null; exceptionOccurred = true; } catch (SOAPException e) { logger.error("SOAP Error: {}", e.getMessage().toString()); exceptionOccurred = true; } finally { // Make sure connection is released. If error occurred make sure to print in log if (exceptionOccurred) { logger.warn("Releasing connection to FritzBox because of error."); resetHttpClient(); } else { logger.debug("Releasing connection"); } postSoap.releaseConnection(); } return response; }
From source file:org.talend.components.jira.connection.Rest.java
/** * Constructor sets schema(http or https), host(google.com) and port number(8080) using one hostPort parameter * /*from ww w .ja v a 2 s . c o m*/ * @param hostPort URL */ public Rest(String hostPort) { headers = new LinkedList<Header>(); if (!hostPort.endsWith("/")) { hostPort = hostPort + "/"; } this.hostPort = hostPort; contentType = ContentType.create("application/json", StandardCharsets.UTF_8); executor = Executor.newInstance(); executor.use(new BasicCookieStore()); }
From source file:org.usc.wechat.mp.sdk.util.HttpUtil.java
public static <T extends JsonRtn> T postBodyRequest(WechatRequest request, License license, Map<String, String> paramMap, Object requestBody, Class<T> jsonRtnClazz) { if (request == null || license == null || requestBody == null || jsonRtnClazz == null) { return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "missing post request params"); }/*from w w w . j a v a 2 s .co m*/ String requestUrl = request.getUrl(); String requestName = request.getName(); List<NameValuePair> nameValuePairs = buildNameValuePairs(license, paramMap); String body = JSONObject.toJSONString(requestBody); URI uri = buildURI(requestUrl, nameValuePairs); if (uri == null) { return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "build request URI failed"); } try { String rtnJson = Request.Post(uri).connectTimeout(CONNECT_TIMEOUT).socketTimeout(SOCKET_TIMEOUT) .bodyString(body, ContentType.create("text/html", Consts.UTF_8)).execute() .handleResponse(HttpUtil.UTF8_CONTENT_HANDLER); T jsonRtn = JsonRtnUtil.parseJsonRtn(rtnJson, jsonRtnClazz); log.info(requestName + " result:\n url={},\n body={},\n rtn={},\n {}", uri, body, rtnJson, jsonRtn); return jsonRtn; } catch (Exception e) { String msg = requestName + " failed:\n url=" + uri + ",\n body=" + body; log.error(msg, e); return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "post request server failed"); } }
From source file:org.wso2.carbon.identity.mgt.endpoint.client.SelfRegistrationMgtClient.java
/** * Checks whether a given username is valid or not. * * @param username Username.//from w w w. j ava2s . c o m * @param skipSignUpCheck To specify whether to enable or disable the check whether sign up is enabled for this * tenant. * @return An integer with status code. * @throws SelfRegistrationMgtClientException Self Registration Management Exception. */ public Integer checkUsernameValidity(String username, boolean skipSignUpCheck) throws SelfRegistrationMgtClientException { boolean isDebugEnabled = log.isDebugEnabled(); try (CloseableHttpClient httpclient = HttpClientBuilder.create().useSystemProperties().build()) { JSONObject user = new JSONObject(); user.put(USERNAME, username); JSONArray properties = new JSONArray(); JSONObject property = new JSONObject(); property.put(KEY, SKIP_SIGN_UP_ENABLE_CHECK); property.put(VALUE, skipSignUpCheck); properties.put(property); user.put(PROPERTIES, properties); HttpPost post = new HttpPost(getUserAPIEndpoint()); setAuthorizationHeader(post); post.setEntity(new StringEntity(user.toString(), ContentType.create( HTTPConstants.MEDIA_TYPE_APPLICATION_JSON, Charset.forName(StandardCharsets.UTF_8.name())))); try (CloseableHttpResponse response = httpclient.execute(post)) { if (isDebugEnabled) { log.debug("HTTP status " + response.getStatusLine().getStatusCode() + " validating username"); } if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { JSONObject jsonResponse = new JSONObject( new JSONTokener(new InputStreamReader(response.getEntity().getContent()))); if (isDebugEnabled) { log.debug("Create response: " + jsonResponse.toString(2)); } return jsonResponse.getInt("statusCode"); } else { // Logging and throwing since this is a client if (log.isDebugEnabled()) { log.debug("Unexpected response code found : " + response.getStatusLine().getStatusCode()); } throw new SelfRegistrationMgtClientException("Error while self registering user : " + username); } } finally { post.releaseConnection(); } } catch (IOException e) { // Logging and throwing since this is a client. if (log.isDebugEnabled()) { log.debug("Error while self registering user : " + username, e); } throw new SelfRegistrationMgtClientException("Error while self registering user : " + username, e); } }
From source file:org.xwiki.extension.repository.xwiki.internal.XWikiExtensionRepository.java
protected CloseableHttpResponse postRESTResource(UriBuilder builder, String content, Object... values) throws IOException { String url;/* www. j a va 2 s .c o m*/ try { url = builder.build(values).toString(); } catch (Exception e) { throw new IOException("Failed to build REST URL", e); } CloseableHttpClient httpClient = this.httpClientFactory.createClient( getDescriptor().getProperty("auth.user"), getDescriptor().getProperty("auth.password")); HttpPost postMethod = new HttpPost(url); postMethod.addHeader("Accept", "application/xml"); StringEntity entity = new StringEntity(content, ContentType.create(ContentType.APPLICATION_XML.getMimeType(), Consts.UTF_8)); postMethod.setEntity(entity); CloseableHttpResponse response; try { if (this.localContext != null) { response = httpClient.execute(postMethod, this.localContext); } else { response = httpClient.execute(postMethod); } } catch (Exception e) { throw new IOException(String.format("Failed to request [%s]", postMethod.getURI()), e); } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException(String.format("Invalid answer [%s] from the server when requesting [%s]", response.getStatusLine().getStatusCode(), postMethod.getURI())); } return response; }
From source file:xin.nic.sdk.registrar.util.HttpUtil.java
public static String doPost(String requestUrl, Map<String, String> paramsMap, Map<String, InputStream> files) throws Exception { RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(500) .setSocketTimeout(20000).setConnectTimeout(20000).build(); // ?//from w w w .j a va2 s.c o m MultipartEntityBuilder mbuilder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName(charset)); if (paramsMap != null) { Set<Entry<String, String>> paramsSet = paramsMap.entrySet(); for (Entry<String, String> entry : paramsSet) { mbuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", charset)); } } if (files != null) { Set<Entry<String, InputStream>> filesSet = files.entrySet(); for (Entry<String, InputStream> entry : filesSet) { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = entry.getValue(); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } os.close(); is.close(); mbuilder.addBinaryBody("attachment", os.toByteArray(), ContentType.APPLICATION_OCTET_STREAM, entry.getKey()); } } HttpPost httpPost = new HttpPost(requestUrl); httpPost.setConfig(requestConfig); HttpEntity httpEntity = mbuilder.build(); httpPost.setEntity(httpEntity); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; return httpClient.execute(httpPost, responseHandler); }