List of usage examples for org.apache.http.entity FileEntity setContentType
public void setContentType(Header header)
From source file:Main.java
/** * Method to initialize and prepare an HttpPost object * @param file/*ww w .j av a 2s . c o m*/ * @param url * @param chunked * @return HttpPost */ public static HttpPost prepareRequest(File file, String url, boolean chunked) { HttpPost post = new HttpPost(url); FileEntity reqEntity = new FileEntity(file, "binary/octet-stream"); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(chunked); post.setEntity(reqEntity); return post; }
From source file:com.mber.client.HTTParty.java
public static Call put(final String url, final File file) throws IOException { FileEntity entity = new FileEntity(file); entity.setContentType("application/octet-stream"); HttpPut request = new HttpPut(url); request.setEntity(entity);//from ww w. j a v a 2 s . c o m return execute(request); }
From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java
/** * <p>Index documents in bulk mode into EL server.</p> */// ww w.j a v a 2s. c o m protected static void addDocuments(CloseableHttpClient httpClient, File dataContentFile) throws Exception { HttpPost httpPost2 = new HttpPost(urlBuilder.getBulk()); FileEntity inputData = new FileEntity(dataContentFile); inputData.setContentType(CONTENTTYPE_JSON); httpPost2.addHeader(HEADER_ACCEPT, CONTENTTYPE_JSON); httpPost2.addHeader(HEADER_CONTENTTYPE, CONTENTTYPE_JSON); httpPost2.setEntity(inputData); CloseableHttpResponse dataResponse = httpClient.execute(httpPost2); if (dataResponse.getStatusLine().getStatusCode() != EL_REST_RESPONSE_OK) { System.out.println("Error response body:"); System.out.println(responseAsString(dataResponse)); } httpPost2.completed(); Assert.assertEquals(dataResponse.getStatusLine().getStatusCode(), EL_REST_RESPONSE_OK); }
From source file:com.platts.portlet.documentlibrary.DLSetSeoUrl.java
@Override public void processAction(StrutsPortletAction originalStrutsPortletAction, PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, SystemException, IOException { LOGGER.info("the process action for struts action DLSetSeoUrl is getting called"); String uri = ParamUtil.getString(actionRequest, "uri", null); String seoURL = ParamUtil.getString(actionRequest, "seoURL", null); Long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId"); LOGGER.info("uri is " + uri + " seourl is " + seoURL + " fileEntryId " + fileEntryId); FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(fileEntryId); // sample url http://10.206.111.1:8030/v1/resources/content?uri=/test/holiday.xml&seoUrl=/EditorBios/regina1233johnson.xml StringBuilder url = new StringBuilder("http://10.206.111.1:8030/v1/resources/content?uri="); url.append(uri).append(StringPool.SLASH).append(fileEntry.getTitle()).append("&seoUrl=").append(seoURL); LOGGER.info("the url is " + url.toString()); PlattsExportUtil exportUtil = new PlattsExportUtil(); ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); File file = exportUtil.getFileFromDLFile(themeDisplay.getUserId(), fileEntry.getFileEntryId(), fileEntry.getLatestFileVersion().getVersion()); //LOGGER.info("the file is " + FileUtils.readFileToString(file)); FileEntity fileEntity = new FileEntity(file); fileEntity.setContentType("application/xml"); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("CPUser", "CPUser22"); credentialsProvider.setCredentials(AuthScope.ANY, credentials); CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(credentialsProvider).build(); HttpPost postRequest = new HttpPost(url.toString()); postRequest.setEntity(fileEntity);/*from w ww . ja v a2 s. c o m*/ try { CloseableHttpResponse response = httpClient.execute(postRequest); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity); Document document = SAXReaderUtil.read(responseString); String responseText = document.getRootElement().selectSingleNode("/response").getText(); if (responseText.equalsIgnoreCase("ok")) { SessionMessages.add(actionRequest, "seoURLActionSuccess"); hideDefaultSuccessMessage(actionRequest); String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect")); try { actionResponse.sendRedirect(redirect); } catch (IOException e) { LOGGER.error("error redirecting ", e); } } else { SessionErrors.add(actionRequest, "seoURLActionFailure"); LOGGER.info("the error text is " + responseText); actionResponse.setRenderParameter("errorMessage", responseText); } response.close(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:gov.nih.nci.system.web.client.RESTfulCreateClient.java
public Response create(File fileLoc, String url) { try {/*from w w w. ja va2s . c o m*/ if (url == null) { ResponseBuilder builder = Response.status(Status.BAD_REQUEST); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INVALID_URL</code>"); buffer.append("<message>Invalid URL: " + url + "</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); return builder.build(); } if (fileLoc == null || !fileLoc.exists()) { ResponseBuilder builder = Response.status(Status.BAD_REQUEST); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INVALID_FILE</code>"); buffer.append("<message>Invalid File given to read</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); return builder.build(); } DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPut putRequest = new HttpPut(url); FileEntity input = new FileEntity(fileLoc); input.setContentType("application/xml"); if (userName != null && password != null) { String base64encodedUsernameAndPassword = new String( Base64.encodeBase64((userName + ":" + password).getBytes())); putRequest.addHeader("Authorization", "Basic " + base64encodedUsernameAndPassword); } putRequest.setEntity(input); HttpResponse response = httpClient.execute(putRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); while ((output = br.readLine()) != null) { buffer.append(output); } ResponseBuilder builder = Response.status(Status.CREATED); builder.type("application/xml"); buffer.append("</response>"); builder.entity(buffer.toString()); httpClient.getConnectionManager().shutdown(); return builder.build(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:gov.nih.nci.system.web.client.RESTfulUpdateClient.java
public Response update(File fileLoc, String url) { try {//w ww . jav a 2 s .c om if (url == null) { System.out.println("Invalid URL"); ResponseBuilder builder = Response.status(Status.BAD_REQUEST); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INVALID_URL</code>"); buffer.append("<message>Invalid URL: " + url + "</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); return builder.build(); } if (fileLoc == null || !fileLoc.exists()) { System.out.println("Invalid file to create"); ResponseBuilder builder = Response.status(Status.BAD_REQUEST); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INVALID_FILE</code>"); buffer.append("<message>Invalid File given to read</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); return builder.build(); } DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(url); FileEntity input = new FileEntity(fileLoc); input.setContentType("application/xml"); if (userName != null && password != null) { String base64encodedUsernameAndPassword = new String( Base64.encodeBase64((userName + ":" + password).getBytes())); postRequest.addHeader("Authorization", "Basic " + base64encodedUsernameAndPassword); } postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); while ((output = br.readLine()) != null) { buffer.append(output); } ResponseBuilder builder = Response.status(Status.CREATED); builder.type("application/xml"); buffer.append("</response>"); builder.entity(buffer.toString()); httpClient.getConnectionManager().shutdown(); return builder.build(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:de.unikassel.android.sdcframework.transmission.SimpleHttpProtocol.java
/** * Method for an HTTP upload of file stream * // www .j a v a2 s .c o m * @param file * the input file * * @return true if successful, false otherwise */ private final boolean httpUpload(File file) { DefaultHttpClient client = new DefaultHttpClient(); try { String fileName = FileUtils.fileNameFromPath(file.getName()); String contentType = getContentType(fileName); URL url = getURL(); configureForAuthentication(client, url); HttpPost httpPost = new HttpPost(url.toURI()); FileEntity fileEntity = new FileEntity(file, contentType); fileEntity.setContentType(contentType); fileEntity.setChunked(true); httpPost.setEntity(fileEntity); httpPost.addHeader("filename", fileName); httpPost.addHeader("uuid", getUuid().toString()); HttpResponse response = client.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); boolean success = statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT; Logger.getInstance().debug(this, "Server returned: " + statusCode); // clean up if necessary HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } if (!success) { doHandleError("Unexpected server response: " + response.getStatusLine()); success = false; } return success; } catch (ClientProtocolException e) { e.printStackTrace(); doHandleError(PROTOCOL_EXCEPTION + ": " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); doHandleError(IO_EXCEPTION + ": " + e.getMessage()); } catch (URISyntaxException e) { setURL(null); doHandleError(INVALID_URL); } finally { client.getConnectionManager().shutdown(); } return false; }
From source file:com.wegas.integration.IntegrationTest.java
private String postJSONFromFile(String url, String jsonFile) throws IOException { HttpPost post = new HttpPost(baseURL + url); setHeaders(post);/* w ww. j ava 2s . c om*/ FileEntity fileEntity = new FileEntity(new File(jsonFile)); fileEntity.setContentType("application/json"); post.setEntity(fileEntity); HttpResponse response = client.execute(post); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); return getEntityAsString(response.getEntity()); }
From source file:test.gov.nih.nci.cacoresdk.domain.operations.ChildTestResourceTest.java
public void testPost() throws Exception { try {//from w w w .j av a 2 s . com DefaultHttpClient httpClient = new DefaultHttpClient(); String url = baseURL + "/rest/ChildTest"; WebClient client = WebClient.create(url); HttpPost postRequest = new HttpPost(url); File myFile = new File("ChildTest" + "XML.xml"); if (!myFile.exists()) { testGet(); myFile = new File("ChildTest" + "XML.xml"); if (!myFile.exists()) return; } FileEntity input = new FileEntity(myFile); input.setContentType("application/xml"); System.out.println("input: " + myFile); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } httpClient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); throw e; } }
From source file:test.gov.nih.nci.cacoresdk.domain.operations.ChildTestResourceTest.java
public void testPut() throws Exception { try {//from ww w . j av a 2 s. c o m DefaultHttpClient httpClient = new DefaultHttpClient(); String url = baseURL + "/rest/ChildTest"; HttpPut putRequest = new HttpPut(url); File myFile = new File("ChildTest" + "XML.xml"); if (!myFile.exists()) { testGet(); myFile = new File("ChildTest" + "XML.xml"); if (!myFile.exists()) return; } FileEntity input = new FileEntity(myFile); input.setContentType("application/xml"); putRequest.setEntity(input); HttpResponse response = httpClient.execute(putRequest); if (response.getEntity() != null) { BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } } httpClient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); throw e; } }