List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder setMode
public MultipartEntityBuilder setMode(final HttpMultipartMode mode)
From source file:com.google.appinventor.components.runtime.MediaStore.java
/** * Asks the Web service to store the given media file. * * @param mediafile The value to store./*from w w w. j av a 2s.co m*/ */ @SimpleFunction public void PostMedia(String mediafile) throws FileNotFoundException { AsyncCallbackPair<String> myCallback = new AsyncCallbackPair<String>() { public void onSuccess(final String response) { androidUIHandler.post(new Runnable() { public void run() { MediaStored(response); } }); } public void onFailure(final String message) { androidUIHandler.post(new Runnable() { public void run() { WebServiceError(message); } }); } }; try { HttpClient client = new DefaultHttpClient(); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); String[] pathtokens = mediafile.split("/"); String newMediaPath; if (pathtokens[0].equals("file:")) { newMediaPath = new java.io.File(new URL(mediafile).toURI()).getAbsolutePath(); } else { newMediaPath = mediafile; } File media = new File(newMediaPath); entityBuilder.addPart("file", new FileBody(media)); HttpEntity entity = entityBuilder.build(); String uploadURL = getUploadUrl(); HttpPost post = new HttpPost(uploadURL); post.setEntity(entity); HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toString(httpEntity); myCallback.onSuccess(result); } catch (Exception e) { e.printStackTrace(); myCallback.onFailure(e.getMessage()); } }
From source file:org.exmaralda.webservices.BASChunkerConnector.java
public String callChunker(File bpfInFile, File audioFile, HashMap<String, Object> otherParameters) throws IOException, JDOMException { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println("Chunker called at " + dateFormat.format(date)); //2016/11/16 12:08:43 System.out.println("Chunker called at " + Date.); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); if (otherParameters != null) { builder.addTextBody("language", (String) otherParameters.get("language")); }/*from w w w. j a v a 2 s. co m*/ builder.addTextBody("aligner", "fast"); builder.addTextBody("force", "rescue"); builder.addTextBody("minanchorlength", "2"); builder.addTextBody("boost_minanchorlength", "3"); // add the text file builder.addBinaryBody("bpf", bpfInFile); // add the audio file builder.addBinaryBody("audio", audioFile); System.out.println("All parameters set. "); // construct a POST request with the multipart entity HttpPost httpPost = new HttpPost(chunkerURL); httpPost.setEntity(builder.build()); System.out.println("URI: " + httpPost.getURI().toString()); HttpResponse response = httpClient.execute(httpPost); HttpEntity result = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200 && result != null) { String resultAsString = EntityUtils.toString(result); /* <WebServiceResponseLink> <success>true</success> <downloadLink>https://clarin.phonetik.uni-muenchen.de:443/BASWebServices/data/2019.01.03_15.58.41_9D4EECAD0791F9E9ED16DF35E66D1485/IDS_ISW_Chunker_Test_16kHz_OHNE_ANFANG.par</downloadLink> <output/> <warnings/> </WebServiceResponseLink> */ // read the XML result string Document doc = FileIO.readDocumentFromString(resultAsString); // check if success == true Element successElement = (Element) XPath.selectSingleNode(doc, "//success"); if (!((successElement != null) && successElement.getText().equals("true"))) { String errorText = "Call to BASChunker was not successful: " + IOUtilities.elementToString(doc.getRootElement(), true); throw new IOException(errorText); } Element downloadLinkElement = (Element) XPath.selectSingleNode(doc, "//downloadLink"); String downloadLink = downloadLinkElement.getText(); // now we have the download link - just need to get the content as text String bpfOutString = downloadText(downloadLink); EntityUtils.consume(result); httpClient.close(); return bpfOutString; //return resultAsString; } else { // something went wrong, throw an exception String reason = statusLine.getReasonPhrase(); throw new IOException(reason); } }
From source file:MainFrame.HttpCommunicator.java
public boolean removeLessons(JSONObject jsObj) throws MalformedURLException, IOException { String response = null;// w w w. j a v a 2 s . co m if (SingleDataHolder.getInstance().isProxyActivated) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword)); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .build(); HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress, SingleDataHolder.getInstance().proxyPort); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); post.setConfig(config); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apideskviewer.getAllLessons", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } else { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apiDeskViewer.removeLesson", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } if (response.equals(new String("\"success\""))) return true; else return false; }
From source file:MainFrame.HttpCommunicator.java
public boolean setPassword(String password, String group) throws IOException { String response = null;/*from w w w . ja v a 2 s . c o m*/ String hashPassword = md5Custom(password); JSONObject jsObj = new JSONObject(); jsObj.put("group", group); jsObj.put("newHash", hashPassword); if (SingleDataHolder.getInstance().isProxyActivated) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword)); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .build(); HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress, SingleDataHolder.getInstance().proxyPort); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); post.setConfig(config); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apideskviewer.getAllLessons", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } else { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apiDeskViewer.updateGroupAccess", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } if (response.equals(new String("\"success\""))) return true; else return false; }
From source file:MainFrame.HttpCommunicator.java
public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel) throws MalformedURLException, IOException { BufferedReader in = null;//ww w . j a va 2 s . c o m if (SingleDataHolder.getInstance().isProxyActivated) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword)); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .build(); HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress, SingleDataHolder.getInstance().proxyPort); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); post.setConfig(config); StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apideskviewer.getAllLessons", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)); in = new BufferedReader(new InputStreamReader(stream)); } else { URL obj = new URL(SingleDataHolder.getInstance().hostAdress); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "apideskviewer.getAllLessons={}"; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); in = new BufferedReader(new InputStreamReader(con.getInputStream())); } JSONParser parser = new JSONParser(); try { Object parsedResponse = parser.parse(in); JSONObject jsonParsedResponse = (JSONObject) parsedResponse; for (int i = 0; i < jsonParsedResponse.size(); i++) { String s = (String) jsonParsedResponse.get(String.valueOf(i)); String[] splittedPath = s.split("/"); DateFormat DF = new SimpleDateFormat("yyyyMMdd"); Date d = DF.parse(splittedPath[1].replaceAll(".bin", "")); Lesson lesson = new Lesson(splittedPath[0], d, false); String group = splittedPath[0]; String date = new SimpleDateFormat("dd.MM.yyyy").format(d); if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) { comboGroups.addItem(group); } if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) { comboDates.addItem(date); } tableModel.addLesson(lesson); } } catch (Exception ex) { } }
From source file:net.ladenthin.snowman.imager.run.uploader.Uploader.java
@Override public void run() { final CImager cs = ConfigurationSingleton.ConfigurationSingleton.getImager(); final String url = cs.getSnowmanServer().getApiUrl(); for (;;) {//from w w w . j a va2 s. c om File obtainedFile; for (;;) { if (WatchdogSingleton.WatchdogSingleton.getWatchdog().getKillFlag() == true) { LOGGER.trace("killFlag == true"); return; } obtainedFile = FileAssignationSingleton.FileAssignationSingleton.obtainFile(); if (obtainedFile == null) { Imager.waitALittleBit(300); continue; } else { break; } } boolean doUpload = true; while (doUpload) { try { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { final HttpPost httppost = new HttpPost(url); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final FileBody fb = new FileBody(obtainedFile, ContentType.APPLICATION_OCTET_STREAM); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(uploadNameCameraimage, fb); builder.addTextBody(uploadNameFilename, obtainedFile.getName()); builder.addTextBody(uploadNameUsername, cs.getSnowmanServer().getUsername()); builder.addTextBody(uploadNamePassword, cs.getSnowmanServer().getPassword()); builder.addTextBody(uploadNameCameraname, cs.getSnowmanServer().getCameraname()); final HttpEntity httpEntity = builder.build(); httppost.setEntity(httpEntity); if (LOGGER.isTraceEnabled()) { LOGGER.trace("executing request " + httppost.getRequestLine()); } try (CloseableHttpResponse response = httpclient.execute(httppost)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("response.getStatusLine(): " + response.getStatusLine()); } final HttpEntity resEntity = response.getEntity(); if (resEntity != null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("RresEntity.getContentLength(): " + resEntity.getContentLength()); } } final String resString = EntityUtils.toString(resEntity).trim(); EntityUtils.consume(resEntity); if (resString.equals(responseSuccess)) { doUpload = false; LOGGER.trace("true: resString.equals(responseSuccess)"); LOGGER.trace("resString: {}", resString); } else { LOGGER.warn("false: resString.equals(responseSuccess)"); LOGGER.warn("resString: {}", resString); // do not flood log files if an error occurred Imager.waitALittleBit(2000); } } } } catch (NoHttpResponseException | SocketException e) { logIOExceptionAndWait(e); } catch (IOException e) { LOGGER.warn("Found unknown IOException", e); } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("delete obtainedFile {}", obtainedFile); } final boolean delete = obtainedFile.delete(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("delete success {}", delete); } FileAssignationSingleton.FileAssignationSingleton.freeFile(obtainedFile); } }
From source file:ai.susi.server.ClientConnection.java
/** * POST request/*w w w . j a v a 2 s.c o m*/ * @param urlstring * @param map * @param useAuthentication * @throws ClientProtocolException * @throws IOException */ public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication) throws ClientProtocolException, IOException { this.httpClient = HttpClients.custom().useSystemProperties() .setConnectionManager(getConnctionManager(useAuthentication)) .setDefaultRequestConfig(defaultRequestConfig).build(); this.request = new HttpPost(urlstring); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (Map.Entry<String, byte[]> entry : map.entrySet()) { entityBuilder.addBinaryBody(entry.getKey(), entry.getValue()); } ((HttpPost) this.request).setEntity(entityBuilder.build()); this.request.setHeader("User-Agent", USER_AGENT); this.init(); }
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 ww .ja v a 2 s .co m } 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:net.yacy.grid.http.ClientConnection.java
/** * POST request/* www.j a v a2 s . c om*/ * @param urlstring * @param map * @param useAuthentication * @throws ClientProtocolException * @throws IOException */ public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication) throws ClientProtocolException, IOException { this.request = new HttpPost(urlstring); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (Map.Entry<String, byte[]> entry : map.entrySet()) { entityBuilder.addBinaryBody(entry.getKey(), entry.getValue()); } ((HttpPost) this.request).setEntity(entityBuilder.build()); this.request.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent); this.init(); }