List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text, Charset charset) throws UnsupportedEncodingException
From source file:com.su.search.client.solrj.PaHttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpRequestBase method = null;// ww w. ja v a 2 s. c om InputStream is = null; SolrParams params = request.getParams(); // modified by wangqiang406 2012-07-27 // ?? if (null != password) { ModifiableSolrParams wparams = new ModifiableSolrParams(params); wparams.set(SimpleIndexClient.KEY_PA_AUTH, password); params = wparams; } Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = this.parser; } // The parser 'wt=' and 'version=' params are used instead of the original // params ModifiableSolrParams wparams = new ModifiableSolrParams(params); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (invariantParams != null) { wparams.add(invariantParams); } params = wparams; int tries = maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = baseUrl + path; boolean isMultipart = (streams != null && streams.size() > 1); LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url); post.setHeader("Content-Charset", "UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<FormBodyPart>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8")))); } else { postParams.add(new BasicNameValuePair(p, v)); } } } } if (isMultipart) { for (ContentStream content : streams) { parts.add(new FormBodyPart(content.getName(), new InputStreamBody(content.getStream(), content.getName()))); } } if (parts.size() > 0) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); for (FormBodyPart p : parts) { entity.addPart(p); } post.setEntity(entity); } else { //not using multipart HttpEntity e; post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8")); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(params, false); HttpPost post = new HttpPost(url + pstr); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if (tries < 1) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } // TODO: move to a interceptor? method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); method.addHeader("User-Agent", AGENT); InputStream respBody = null; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents String charset = EntityUtils.getContentCharSet(response.getEntity()); respBody = response.getEntity().getContent(); // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; case HttpStatus.SC_NOT_FOUND: throw new SolrServerException("Server at " + getBaseURL() + " was not found (404)."); default: throw new SolrServerException("Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase()); } NamedList<Object> rsp = processor.processResponse(respBody, charset); if (httpStatus != HttpStatus.SC_OK) { String reason = null; try { NamedList err = (NamedList) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); // TODO? get the trace? } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append("request: " + method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), reason); } return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (respBody != null) { try { respBody.close(); } catch (Throwable t) { } // ignore } } }
From source file:gov.nist.appvet.tool.AsynchronousService.java
public void sendReport(String appid, String toolrisk, String reportPath) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 30000); HttpConnectionParams.setSoTimeout(httpParameters, 1200000); HttpClient httpclient = new DefaultHttpClient(httpParameters); httpclient = SSLWrapper.wrapClient(httpclient); try {/*w w w .jav a2 s . co m*/ // To send reports back to AppVet, the following parameters must // be sent: // * command: SUBMIT_REPORT // * username: AppVet username // * password: AppVet password // * appid: The app ID // * toolid: The ID of this tool // * toolrisk: The risk assessment (PASS,FAIL,WARNING,ERROR) // * file: The report file. MultipartEntity entity = new MultipartEntity(); entity.addPart("command", new StringBody("SUBMIT_REPORT", Charset.forName("UTF-8"))); entity.addPart("username", new StringBody(Properties.appVetUsername, Charset.forName("UTF-8"))); entity.addPart("password", new StringBody(Properties.appVetPassword, Charset.forName("UTF-8"))); entity.addPart("appid", new StringBody(appid, Charset.forName("UTF-8"))); entity.addPart("toolid", new StringBody(Properties.toolId, Charset.forName("UTF-8"))); entity.addPart("toolrisk", new StringBody(toolrisk, Charset.forName("UTF-8"))); File report = new File(reportPath); FileBody fileBody = new FileBody(report); entity.addPart("file", fileBody); HttpPost httpPost = new HttpPost(Properties.appVetURL); httpPost.setEntity(entity); log.debug("Sending report to AppVet"); // Send the app to the tool final HttpResponse response = httpclient.execute(httpPost); httpPost = null; log.debug("Received: " + response.getStatusLine()); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.openestate.is24.restapi.hc42.HttpComponents42Client.java
@Override protected Response sendVideoUploadRequest(URL url, RequestMethod method, String auth, InputStream input, String fileName, final long fileSize) throws IOException, OAuthException { if (method == null) method = RequestMethod.POST;/*from w w w . j a va2 s . co m*/ if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method)) throw new IllegalArgumentException("Invalid request method!"); HttpUriRequest request = null; if (RequestMethod.POST.equals(method)) { request = new HttpPost(url.toString()); } else if (RequestMethod.PUT.equals(method)) { request = new HttpPut(url.toString()); } else { throw new IOException("Unsupported request method '" + method + "'!"); } MultipartEntity requestMultipartEntity = new MultipartEntity(); request.setHeader("MIME-Version", "1.0"); request.addHeader(requestMultipartEntity.getContentType()); request.setHeader("Content-Language", "en-US"); request.setHeader("Accept-Charset", "UTF-8"); request.setHeader("Accept-Encoding", "gzip,deflate"); request.setHeader("Connection", "close"); // add auth part to the multipart entity auth = StringUtils.trimToNull(auth); if (auth != null) { StringBody authPart = new StringBody(auth, Charset.forName(getEncoding())); requestMultipartEntity.addPart("auth", authPart); } // add file part to the multipart entity if (input != null) { fileName = StringUtils.trimToNull(fileName); if (fileName == null) fileName = "upload.bin"; //InputStreamBody filePart = new InputStreamBody( input, fileName ); InputStreamBody filePart = new InputStreamBodyWithLength(input, fileName, fileSize); requestMultipartEntity.addPart("videofile", filePart); } // add multipart entity to the request ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity); // sign request //getAuthConsumer().sign( request ); // send request HttpResponse response = httpClient.execute(request); // create response return createResponse(response); }
From source file:gov.nist.appvet.toolmgr.ToolServiceAdapter.java
public MultipartEntity getMultipartEntity() { final MultipartEntity entity = new MultipartEntity(); File apkFile = null;/*from www. ja v a 2 s. co m*/ FileBody fileBody = null; try { String fileUploadParamName = null; // Add parameter name-value pairs if (formParameterNames != null) { for (int i = 0; i < formParameterNames.size(); i++) { final String paramName = formParameterNames.get(i); String paramValue = formParameterValues.get(i); if (paramValue.equals("APP_FILE")) { fileUploadParamName = paramName; } else { if (paramValue.equals("APPVET_DEFINED")) { if (paramName.equals("appid")) { appInfo.log.debug("Found " + paramName + " = " + "'APPVET_DEFINED' for tool '" + id + "'. Setting to appid = '" + appInfo.appId + "'"); paramValue = appInfo.appId; } else { appInfo.log.error("Found " + paramName + " = " + "'APPVET_DEFINED' for tool '" + id + "' but no actual value is set by AppVet. Aborting."); return null; } } if ((paramName == null) || paramName.isEmpty()) { appInfo.log.warn("Param name is null or empty " + "for tool '" + name + "'"); } else if ((paramValue == null) || paramValue.isEmpty()) { appInfo.log.warn("Param value is null or empty " + "for tool '" + name + "'"); } StringBody partValue = new StringBody(paramValue, Charset.forName("UTF-8")); entity.addPart(paramName, partValue); partValue = null; } } } final String apkFilePath = appInfo.getIdPath() + "/" + appInfo.fileName; appInfo.log.debug("Sending file: " + apkFilePath); apkFile = new File(apkFilePath); fileBody = new FileBody(apkFile); entity.addPart(fileUploadParamName, fileBody); return entity; } catch (final UnsupportedEncodingException e) { appInfo.log.error(e.getMessage()); return null; } }
From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java
/** * @throws MLHttpClientException//from w ww.j a va2 s . c o m */ public CloseableHttpResponse predictFromCSV(long modelId, String resourcePath) throws MLHttpClientException { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/models/predict"); httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey()); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addPart("modelId", new StringBody(modelId + "", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN)); if (resourcePath != null) { File file = new File(getResourceAbsolutePath(resourcePath)); multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, "IndiansDiabetesPredict.csv"); } httpPost.setEntity(multipartEntityBuilder.build()); return httpClient.execute(httpPost); } catch (Exception e) { throw new MLHttpClientException("Failed to predict from csv " + resourcePath, e); } }
From source file:com.ebixio.virtmus.stats.StatsLogger.java
/** Should only be called from uploadLogs(). Compresses all files that belong to the given log set, and uploads all compressed files to the server. */ private boolean uploadLogs(final String logSet) { if (logSet == null) return false; File logsDir = getLogsDir();/*from w w w. ja v a 2 s . c om*/ if (logsDir == null) return false; gzipLogs(logsDir, logSet); // Uploading only gz'd files FilenameFilter gzFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".gz"); } }; File[] toUpload = logsDir.listFiles(gzFilter); String url = getUploadUrl(); if (url == null) { /* This means the server is unable to accept the logs. */ keepRecents(toUpload, 100); return false; } CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); addHttpHeaders(post); MultipartEntityBuilder entity = MultipartEntityBuilder.create(); entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("InstallId", new StringBody(String.valueOf(MainApp.getInstallId()), ContentType.TEXT_PLAIN)); ContentType ct = ContentType.create("x-application/gzip"); for (File f : toUpload) { entity.addPart("VirtMusStats", new FileBody(f, ct, f.getName())); } post.setEntity(entity.build()); boolean success = false; try (CloseableHttpResponse response = client.execute(post)) { int status = response.getStatusLine().getStatusCode(); Log.log(Level.INFO, "Log upload result: {0}", status); if (status == HttpStatus.SC_OK) { // 200 for (File f : toUpload) { try { f.delete(); } catch (SecurityException ex) { } } success = true; } else { LogRecord rec = new LogRecord(Level.INFO, "Server Err"); rec.setParameters(new Object[] { url, "Status: " + status }); getLogger().log(rec); } HttpEntity rspEntity = response.getEntity(); EntityUtils.consume(rspEntity); client.close(); } catch (IOException ex) { Log.log(ex); } keepRecents(toUpload, 100); // In case of exceptions or errors return success; }
From source file:co.aurasphere.botmill.fb.internal.util.network.NetworkUtils.java
/** * POSTs a message as a JSON string to Facebook. * * @param recipient// w w w. ja v a 2s .co m * the recipient * @param type * the type * @param file * the file */ public static void postFormDataMessage(String recipient, AttachmentType type, File file) { String pageToken = FbBotMillContext.getInstance().getPageToken(); // If the page token is invalid, returns. if (!validatePageToken(pageToken)) { return; } // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO) HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken); FileBody filedata = new FileBody(file); StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}", ContentType.MULTIPART_FORM_DATA); StringBody messagePart = new StringBody( "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}", ContentType.MULTIPART_FORM_DATA); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.STRICT); builder.addPart("recipient", recipientPart); builder.addPart("message", messagePart); // builder.addPart("filedata", filedata); builder.addBinaryBody("filedata", file); builder.setContentType(ContentType.MULTIPART_FORM_DATA); // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW"); HttpEntity entity = builder.build(); post.setEntity(entity); // Logs the raw JSON for debug purposes. BufferedReader br; // post.addHeader("Content-Type", "multipart/form-data"); try { // br = new BufferedReader(new InputStreamReader( // ()))); Header[] allHeaders = post.getAllHeaders(); for (Header h : allHeaders) { logger.debug("Header {} -> {}", h.getName(), h.getValue()); } // String output = br.readLine(); } catch (Exception e) { e.printStackTrace(); } send(post); }
From source file:sk.datalan.solr.impl.HttpSolrServer.java
protected HttpRequestBase createMethod(final SolrRequest request) throws IOException, SolrServerException { HttpRequestBase method = null;//from ww w. ja v a 2 s. co m InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = this.parser; } // The parser 'wt=' and 'version=' params are used instead of the original // params ModifiableSolrParams wparams = new ModifiableSolrParams(params); if (parser != null) { wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); } if (invariantParams != null) { wparams.add(invariantParams); } int tries = maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = baseUrl + path; boolean hasNullStreamName = false; if (streams != null) { for (ContentStream cs : streams) { if (cs.getName() == null) { hasNullStreamName = true; break; } } } boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1)) && !hasNullStreamName; // only send this list of params as query string params ModifiableSolrParams queryParams = new ModifiableSolrParams(); for (String param : this.queryParams) { String[] value = wparams.getParams(param); if (value != null) { for (String v : value) { queryParams.add(param, v); } wparams.remove(param); } } LinkedList<NameValuePair> postParams = new LinkedList<>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false)); post.setHeader("Content-Charset", "UTF-8"); if (!isMultipart) { post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<>(); Iterator<String> iter = wparams.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = wparams.getParams(p); if (vals != null) { for (String v : vals) { if (isMultipart) { parts.add( new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8))); } else { postParams.add(new BasicNameValuePair(p, v)); } } } } if (isMultipart && streams != null) { for (ContentStream content : streams) { String contentType = content.getContentType(); if (contentType == null) { contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default } String name = content.getName(); if (name == null) { name = ""; } parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName()))); } } if (parts.size() > 0) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); for (FormBodyPart p : parts) { entity.addPart(p); } post.setEntity(entity); } else { //not using multipart post.setEntity(new UrlEncodedFormEntity(postParams, StandardCharsets.UTF_8)); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(wparams, false); HttpPost post = new HttpPost(url + pstr); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if (tries < 1) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } return method; }
From source file:pl.psnc.synat.wrdz.zmkd.plan.MigrationPlanProcessorBean.java
/** * Creates a new object in ZMD./*from w w w .j a v a 2 s. co m*/ * * @param client * http client instance * @param files * map of the new object's files; keys contain the file names/paths inside the new object's structure * @param fileSequence * map of the new object's file sequence values; keys contain the file names/paths inside the new * object's structure * @param originIdentifier * identifier of the object the new object was migrated from * @param originType * the type of migration performed * @return creation request identifier * @throws IOException * if object upload fails */ private String saveObject(HttpClient client, Map<String, File> files, Map<String, Integer> fileSequence, String originIdentifier, MigrationType originType) throws IOException { DateFormat format = new SimpleDateFormat(ORIGIN_DATE_FORMAT); HttpPost post = new HttpPost(zmkdConfiguration.getZmdObjectUrl()); MultipartEntity entity = new MultipartEntity(); try { entity.addPart(ORIGIN_ID, new StringBody(originIdentifier, ENCODING)); entity.addPart(ORIGIN_TYPE, new StringBody(originType.name(), ENCODING)); entity.addPart(ORIGIN_DATE, new StringBody(format.format(new Date()), ENCODING)); int i = 0; for (Entry<String, File> dataFile : files.entrySet()) { FileBody file = new FileBody(dataFile.getValue()); StringBody path = new StringBody(dataFile.getKey(), ENCODING); entity.addPart(String.format(FILE_SRC, i), file); entity.addPart(String.format(FILE_DEST, i), path); if (fileSequence.containsKey(dataFile.getKey())) { StringBody seq = new StringBody(fileSequence.get(dataFile.getKey()).toString(), ENCODING); entity.addPart(String.format(FILE_SEQ, i), seq); } i++; } } catch (UnsupportedEncodingException e) { throw new WrdzRuntimeException("The encoding " + ENCODING + " is not supported"); } post.setEntity(entity); HttpResponse response = client.execute(post); EntityUtils.consumeQuietly(response.getEntity()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) { String location = response.getFirstHeader("location").getValue(); return location.substring(location.lastIndexOf('/') + 1); } else { throw new IOException("Unexpected response: " + response.getStatusLine()); } }