List of usage examples for org.apache.http.entity ContentType create
private static ContentType create(HeaderElement headerElement)
From source file:com.evrythng.java.wrapper.util.FileUtils.java
/** * Uploads a {@code File} with PRIVATE read access. * * @param uri upload {@link URI}//from w w w .ja v a2 s . c om * @param contentTypeString content type * @param contentFile the file to upload * @throws IOException */ public static void uploadPrivateContent(final URI uri, final String contentTypeString, final File contentFile) throws IOException { LOGGER.info("uploadPrivateContent START: uri: [{}]; content type: [{}], content file: [{}]", new Object[] { uri, contentTypeString, contentFile }); CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(uri); httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString); httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE); ContentType contentType = ContentType.create(contentTypeString); FileEntity fileEntity = new FileEntity(contentFile, contentType); httpPut.setEntity(fileEntity); CloseableHttpResponse response = closeableHttpClient.execute(httpPut); StatusLine statusLine = response.getStatusLine(); if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) { throw new IOException(String.format("An error occurred while trying to upload private file - %d: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase())); } LOGGER.info("uploadPrivateContent END: uri: [{}]; content type: [{}], content file: [{}]", new Object[] { uri, contentTypeString, contentFile }); }
From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java
@Override public final <RQ, RS> Will<Response<RS>> post(String resource, RQ rq, Class<RS> clazz) throws RestEndpointIOException { HttpPost post = new HttpPost(spliceUrl(resource)); Serializer serializer = getSupportedSerializer(rq); ByteArrayEntity httpEntity = new ByteArrayEntity(serializer.serialize(rq), ContentType.create(serializer.getMimeType())); post.setEntity(httpEntity);/*from w ww . j a v a 2 s . co m*/ return executeInternal(post, new ClassConverterCallback<RS>(serializers, clazz)); }
From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java
/** * Uploads the specified file to the community site. The return identifier * can be used later when composing other requests. * /*from ww w. j a v a 2 s . co m*/ * @param httpclient * the http client * @param attachment * the file to attach * @param authCookie * the session cookie to use for authentication purpose * @return the identifier of the file uploaded, <code>null</code> otherwise * @throws CommunityAPIException */ public static String uploadFile(CloseableHttpClient httpclient, File attachment, Cookie authCookie) throws CommunityAPIException { FileInputStream fin = null; try { fin = new FileInputStream(attachment); byte fileContent[] = new byte[(int) attachment.length()]; fin.read(fileContent); byte[] encodedFileContent = Base64.encodeBase64(fileContent); FileUploadRequest uploadReq = new FileUploadRequest(attachment.getName(), encodedFileContent); HttpPost fileuploadPOST = new HttpPost(CommunityConstants.FILE_UPLOAD_URL); EntityBuilder fileUploadEntity = EntityBuilder.create(); fileUploadEntity.setText(uploadReq.getAsJSON()); fileUploadEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE)); fileUploadEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET); fileuploadPOST.setEntity(fileUploadEntity.build()); CloseableHttpResponse resp = httpclient.execute(fileuploadPOST); int httpRetCode = resp.getStatusLine().getStatusCode(); String responseBodyAsString = EntityUtils.toString(resp.getEntity()); if (HttpStatus.SC_OK == httpRetCode) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); JsonNode jsonRoot = mapper.readTree(responseBodyAsString); String fid = jsonRoot.get("fid").asText(); //$NON-NLS-1$ return fid; } else { CommunityAPIException ex = new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError); ex.setHttpStatusCode(httpRetCode); ex.setResponseBodyAsString(responseBodyAsString); throw ex; } } catch (FileNotFoundException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_FileNotFoundError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } catch (UnsupportedEncodingException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } catch (IOException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } finally { IOUtils.closeQuietly(fin); } }
From source file:org.camunda.bpm.engine.rest.standalone.AbstractEmptyBodyFilterTest.java
@Test public void testBodyIsEmptyJSONObject() throws IOException { evaluatePostRequest(new ByteArrayEntity(EMPTY_JSON_OBJECT.getBytes("UTF-8")), ContentType.create(MediaType.APPLICATION_JSON).toString(), 200, true); }
From source file:pl.psnc.synat.wrdz.zmkd.invocation.RestServiceCallerUtils.java
/** * Constructs octet-stream entity based upon the specified value or the file and its mimetype (ie. request * parameter)./* w w w . j a v a2s. c o m*/ * * @param requestParam * request parameter * @return request octet-stream entity for the service */ private static HttpEntity constructOctetStreamEntity(ExecutionBodyParam requestParam) { if (requestParam == null) { return null; } if (requestParam.getValue() != null) { return new StringEntity(requestParam.getValue(), TEXTPLAIN); } if (requestParam.getFileValue() != null) { try { ContentType contentType = ContentType.create(requestParam.getFileValue().getMimetype()); return new FileEntity(requestParam.getFileValue().getFile(), contentType); } catch (IllegalArgumentException e) { return new FileEntity(requestParam.getFileValue().getFile()); } } return null; }
From source file:org.n52.oss.sir.Client.java
private XmlObject doSend(String request, String requestMethod, URI requestUri) { log.debug("Sending request (first 100 characters): {}", request.substring(0, Math.min(request.length(), 100))); if (requestUri == null) { OwsExceptionReport oer = new OwsExceptionReport(ExceptionCode.NoApplicableCode, requestMethod, "given URL is null for request " + request); return oer.getDocument(); }//www. j ava 2s .co m try (CloseableHttpClient client = httpClientBuilder.build();) { HttpRequestBase method = null; if (requestMethod.equals(GET_METHOD)) { log.debug("Client connecting via GET to '{}' with request '{}'", requestUri, request); String fullUri = null; if (request == null || request.isEmpty()) fullUri = requestUri.toString(); else fullUri = requestUri.toString() + "?" + request; log.debug("GET call: {}", fullUri); HttpGet get = new HttpGet(fullUri); method = get; } else if (requestMethod.equals(POST_METHOD)) { log.debug("Client connecting via POST to {}", requestUri); HttpPost postMethod = new HttpPost(requestUri.toString()); postMethod.setEntity( new StringEntity(request, ContentType.create(SirConstants.REQUEST_CONTENT_TYPE))); method = postMethod; } else { throw new IllegalArgumentException("requestMethod not supported!"); } try { HttpResponse httpResponse = client.execute(method); try (InputStream is = httpResponse.getEntity().getContent();) { XmlObject responseObject = XmlObject.Factory.parse(is); return responseObject; } } catch (XmlException e) { log.error("Error parsing response.", e); // TODO add handling to identify HTML response // if (responseString.contains(HTML_TAG_IN_RESPONSE)) { // log.error("Received HTML!\n" + responseString + "\n"); // } String msg = "Could not parse response (received via " + requestMethod + ") to the request\n\n" + request + "\n\n\n" + Tools.getStackTrace(e); // msg = msg + "\n\nRESPONSE STRING:\n<![CDATA[" + responseObject.xmlText() + "]]>"; OwsExceptionReport er = new OwsExceptionReport(ExceptionCode.NoApplicableCode, "Client.doSend()", msg); return er.getDocument(); } catch (Exception e) { log.error("Error executing method on httpClient.", e); return new OwsExceptionReport(ExceptionCode.NoApplicableCode, "service", e.getMessage()) .getDocument(); } } catch (IOException e) { log.error("Could not create http client.", e); return null; } }
From source file:apiserver.core.connectors.coldfusion.ColdFusionHttpBridge.java
public ResponseEntity invokeFilePost(String cfcPath_, String method_, Map<String, Object> methodArgs_) throws ColdFusionException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpHost host = new HttpHost(cfHost, cfPort, cfProtocol); HttpPost method = new HttpPost(validatePath(cfPath) + cfcPath_); MultipartEntityBuilder me = MultipartEntityBuilder.create(); me.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); if (methodArgs_ != null) { for (String s : methodArgs_.keySet()) { Object obj = methodArgs_.get(s); if (obj != null) { if (obj instanceof String) { me.addTextBody(s, (String) obj); } else if (obj instanceof Integer) { me.addTextBody(s, ((Integer) obj).toString()); } else if (obj instanceof File) { me.addBinaryBody(s, (File) obj); } else if (obj instanceof IDocument) { me.addBinaryBody(s, ((IDocument) obj).getFile()); //me.addTextBody( "name", ((IDocument)obj).getFileName() ); //me.addTextBody("contentType", ((IDocument) obj).getContentType().contentType ); } else if (obj instanceof IDocument[]) { for (int i = 0; i < ((IDocument[]) obj).length; i++) { IDocument iDocument = ((IDocument[]) obj)[i]; me.addBinaryBody(s, iDocument.getFile()); //me.addTextBody("name", iDocument.getFileName() ); //me.addTextBody("contentType", iDocument.getContentType().contentType ); }//from w w w . ja v a 2s. c om } else if (obj instanceof BufferedImage) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write((BufferedImage) obj, "jpg", baos); String _fileName = (String) methodArgs_.get(ApiServerConstants.FILE_NAME); String _mimeType = ((MimeType) methodArgs_.get(ApiServerConstants.CONTENT_TYPE)) .getExtension(); ContentType _contentType = ContentType.create(_mimeType); me.addBinaryBody(s, baos.toByteArray(), _contentType, _fileName); } else if (obj instanceof byte[]) { me.addBinaryBody(s, (byte[]) obj); } else if (obj instanceof Map) { ObjectMapper mapper = new ObjectMapper(); String _json = mapper.writeValueAsString(obj); me.addTextBody(s, _json); } } } } HttpEntity httpEntity = me.build(); method.setEntity(httpEntity); HttpResponse response = httpClient.execute(host, method);//, responseHandler); // Examine the response status if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Get hold of the response entity HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); //return inputStream; byte[] _body = IOUtils.toByteArray(inputStream); MultiValueMap _headers = new LinkedMultiValueMap(); for (Header header : response.getAllHeaders()) { if (header.getName().equalsIgnoreCase("content-length")) { _headers.add(header.getName(), header.getValue()); } else if (header.getName().equalsIgnoreCase("content-type")) { _headers.add(header.getName(), header.getValue()); // special condition to add zip to the file name. if (header.getValue().indexOf("text/") > -1) { //add nothing extra } else if (header.getValue().indexOf("zip") > -1) { if (methodArgs_.get("file") != null) { String _fileName = ((Document) methodArgs_.get("file")).getFileName(); _headers.add("Content-Disposition", "attachment; filename=\"" + _fileName + ".zip\""); } } else if (methodArgs_.get("file") != null) { String _fileName = ((Document) methodArgs_.get("file")).getFileName(); _headers.add("Content-Disposition", "attachment; filename=\"" + _fileName + "\""); } } } return new ResponseEntity(_body, _headers, org.springframework.http.HttpStatus.OK); //Map json = (Map)deSerializeJson(inputStream); //return json; } } MultiValueMap _headers = new LinkedMultiValueMap(); _headers.add("Content-Type", "text/plain"); return new ResponseEntity(response.getStatusLine().toString(), _headers, org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } }
From source file:org.craftercms.engine.http.impl.HttpProxyImpl.java
protected void copyOriginalRequestBody(HttpPost httpRequest, HttpServletRequest request) throws IOException { int contentLength = request.getContentLength(); if (contentLength > 0) { String contentType = request.getContentType(); InputStream content = request.getInputStream(); httpRequest.setEntity(new InputStreamEntity(content, contentLength, ContentType.create(contentType))); }/* w w w . ja v a 2 s . c o m*/ }