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:ua.pp.msk.maven.MavenHttpClient.java
private int execute(File file) throws ArtifactPromotingException { CloseableHttpClient client = HttpClientBuilder.create().build(); int status = -1; try {//w w w . ja va 2s . c om getLog().debug("Connecting to URL: " + url); HttpPost post = new HttpPost(url); post.setHeader("User-Agent", userAgent); if (username != null && username.length() != 0 && password != null) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); post.addHeader(new BasicScheme().authenticate(creds, post, null)); } if (file == null) { if (!urlParams.isEmpty()) { post.setEntity(new UrlEncodedFormEntity(urlParams)); } } else { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (!urlParams.isEmpty()) { for (NameValuePair nvp : urlParams) { builder.addPart(nvp.getName(), new StringBody(nvp.getValue(), ContentType.MULTIPART_FORM_DATA)); } } FileBody fb = new FileBody(file); // Not used because of form submission // builder.addBinaryBody("file", file, // ContentType.DEFAULT_BINARY, file.getName()); builder.addPart("file", fb); HttpEntity sendEntity = builder.build(); post.setEntity(sendEntity); } CloseableHttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); status = statusLine.getStatusCode(); getLog().info( "Response status code: " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase()); // Perhaps I need to parse html // String html = EntityUtils.toString(entity); } catch (AuthenticationException ex) { throw new ArtifactPromotingException(ex); } catch (UnsupportedEncodingException ex) { throw new ArtifactPromotingException(ex); } catch (IOException ex) { throw new ArtifactPromotingException(ex); } finally { try { client.close(); } catch (IOException ex) { throw new ArtifactPromotingException("Cannot close http client", ex); } } return status; }
From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java
/** * Trains the ranker using the trainingdata.csv * //from ww w. j a v a2s . c o m * @param ranker_url URL associated with the ranker Ex.) * "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/rankers" * @param rankerName The name of the ranker, to be sent as metadata * @param client {@link HttpClient} to send the request to * @param training_file Path to the trainingdata.csv * @return JSON of the result: { "name": "example-ranker", "url": * "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/rankers/6C76AF-ranker-43", * "ranker_id": "6C76AF-ranker-43", "created": "2015-09-21T18:01:57.393Z", "status": * "Training", "status_description": * "The ranker instance is in its training phase, not yet ready to accept requests" } * @throws IOException */ public static String trainRanker(String ranker_url, String rankerName, HttpClient client, StringBuffer training_data) throws IOException { // Create a POST request HttpPost post = new HttpPost(ranker_url); MultipartEntityBuilder postParams = MultipartEntityBuilder.create(); // Add data String metadata = "\"" + rankerName + "\""; StringBody metadataBody = new StringBody(metadata, ContentType.TEXT_PLAIN); postParams.addPart(RetrieveAndRankSearcherConstants.TRAINING_DATA_LABEL, new AnswerFileBody(training_data.toString())); postParams.addPart(RetrieveAndRankSearcherConstants.TRAINING_METADATA_LABEL, metadataBody); post.setEntity(postParams.build()); // Obtain and parse response HttpResponse response = client.execute(post); String result = getHttpResultString(response); return result; }
From source file:de.geomobile.joined.api.service.JOWebService.java
/** * Register for FriendFinder users. The nickname and password are mandatory. * //from w w w .j a v a 2s .co m * @param name * The users nickname. * @param password * The users password. * @param profilImage * The users profile image exists. * @return the generated attributes userid and secureToken as json object. * @throws JOFriendFinderHTTPException * when another exception runs * @throws JOFriendFinderUnexpectedException * @throws JOFriendFinderServerException * @throws JOFriendFinderConflictException * when nickname already exists */ public String ffRegister(String name, String password) throws JOFriendFinderHTTPException, JOFriendFinderUnexpectedException, JOFriendFinderServerException, JOFriendFinderConflictException { try { // String hash = getSHA1Hash(name + getJoinedSecretSalt()); // HttpPost httppost = new HttpPost(getJoinedServerUrl() + Config.FF_REGISTER + Config.HASH + hash); HttpPost httppost = new HttpPost(getJoinedServerUrl() + JOConfig.FF_REGISTER + "/" + getJoinedApiKey()); MultipartEntity entity = new MultipartEntity(); entity.addPart(JOConfig.NICKNAME, new StringBody(name, Charset.forName(JOConfig.UTF_8))); entity.addPart(JOConfig.PASSWORD, new StringBody(getSHA1Hash(password + name), Charset.forName(JOConfig.UTF_8))); // entity.addPart(Config.IMAGE_KEY, new FileBody(new File(Config.MEDIA_PATH + Config.IMAGE_PNG))); // entity.addPart(Config.IMAGE_HASH, new StringBody(calculateHash(Config.MEDIA_PATH + Config.IMAGE_PNG), Charset.forName(Config.UTF_8))); httppost.setEntity(entity); HttpClient httpClient = getNewHttpClient(); HttpResponse httpResponse = httpClient.execute(httppost); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) { throw new JOFriendFinderServerException(); } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CONFLICT) { throw new JOFriendFinderConflictException(); } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new JOFriendFinderUnexpectedException( "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode()); } else { return getJsonStringFromResponse(httpResponse); } } catch (GeneralSecurityException e) { throw new JOFriendFinderUnexpectedException(e); } catch (UnsupportedEncodingException e) { throw new JOFriendFinderUnexpectedException(e); } catch (ClientProtocolException e) { throw new JOFriendFinderHTTPException(e); } catch (IOException e) { throw new JOFriendFinderHTTPException(e); } catch (Exception e) { throw new JOFriendFinderUnexpectedException(e); } }
From source file:outfox.dict.contest.util.FileUtils.java
/** * ?NOSurl/*from w ww. ja v a 2 s . c om*/ * @param bytes * @return */ public static String uploadFile2Nos(byte[] bytes) { if (bytes == null) { return null; } HttpResponse response = null; String result = null; try { FileBody bin = new FileBody( FileUtils.getFileFromBytes(bytes, "tmpfile/file-" + System.currentTimeMillis())); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("video", new StringBody("true", Charset.forName("UTF-8"))); // reqEntity.addPart("contentType", new StringBody("audio/mpeg", Charset.forName("UTF-8"))); response = HttpToolKit.getInstance().doPost(ContestConsts.NOS_UPLOAD_Interface, reqEntity); if (response != null) { String jsonString = EntityUtils.toString(response.getEntity()); JSONObject json = JSON.parseObject(jsonString); if ("success".equals(json.getString("msg"))) { return json.getString("url"); } } } catch (Exception e) { LOG.error("FileUtils.uploadFile2Nos(bytes) error...", e); } finally { HttpToolKit.closeQuiet(response); } return result; }
From source file:objective.taskboard.it.TemplateIT.java
private HttpResponse uploadTemplate(File file) throws URISyntaxException, IOException { FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); StringBody templateName = new StringBody(file.getName(), ContentType.MULTIPART_FORM_DATA); StringBody roles = new StringBody("Role", ContentType.MULTIPART_FORM_DATA); builder.addPart("file", fileBody); builder.addPart("name", templateName); builder.addPart("roles", roles); HttpEntity entity = builder.build(); HttpPost post = new HttpPost(); post.setURI(new URI("http://localhost:8900/api/templates")); post.setHeaders(session);/*from w w w . j a v a2 s. com*/ post.setEntity(entity); return client.execute(post); }
From source file:net.idea.opentox.cli.dataset.DatasetClient.java
@Override protected HttpEntity createPOSTEntity(Dataset dataset, List<POLICY_RULE> accessRights) throws InvalidInputException, Exception { if (dataset.getInputData() == null || dataset.getInputData().getInputFile() == null) throw new InvalidInputException("File to import not defined!"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8); entity.addPart(_WEBFORM.title.name(), new StringBody(dataset.getMetadata().getTitle(), utf8)); entity.addPart(_WEBFORM.seeAlso.name(), new StringBody(dataset.getMetadata().getSeeAlso(), utf8)); entity.addPart(_WEBFORM.license.name(), new StringBody(dataset.getMetadata().getRights() == null ? "" : (dataset.getMetadata().getRights().getURI() == null ? "" : dataset.getMetadata().getRights().getURI()), utf8));/* w w w. j a v a 2 s . c om*/ entity.addPart(_WEBFORM.match.name(), new StringBody(dataset.getInputData().getImportMatchMode().name(), utf8)); entity.addPart(_WEBFORM.file.name(), new FileBody(dataset.getInputData().getInputFile())); return entity; }
From source file:com.fanfou.app.opensource.util.NetworkHelper.java
public static MultipartEntity encodeMultipartParameters(final List<SimpleRequestParam> params) { if (CommonHelper.isEmpty(params)) { return null; }//from ww w. ja va 2 s .c o m final MultipartEntity entity = new MultipartEntity(); try { for (final SimpleRequestParam param : params) { if (param.isFile()) { entity.addPart(param.getName(), new FileBody(param.getFile())); } else { entity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName(HTTP.UTF_8))); } } } catch (final UnsupportedEncodingException e) { e.printStackTrace(); } return entity; }
From source file:gov.nist.appvet.tool.synchtest.util.ReportUtil.java
/** This method should be used for sending files back to AppVet. */ public static boolean sendInNewHttpRequest(String appId, String reportFilePath, ToolStatus reportStatus) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 30000); HttpConnectionParams.setSoTimeout(httpParameters, 1200000); HttpClient httpClient = new DefaultHttpClient(httpParameters); httpClient = SSLWrapper.wrapClient(httpClient); try {/*from www . ja v a 2 s .c o 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 (LOW, MODERATE, HIGH, * ERROR) - report: 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(reportStatus.name(), Charset.forName("UTF-8"))); File report = new File(reportFilePath); FileBody fileBody = new FileBody(report); entity.addPart("file", fileBody); HttpPost httpPost = new HttpPost(Properties.appvetUrl); httpPost.setEntity(entity); // Send the report to AppVet log.debug("Sending report file to AppVet"); final HttpResponse response = httpClient.execute(httpPost); log.debug("Received from AppVet: " + response.getStatusLine()); // Clean up httpPost = null; return true; } catch (Exception e) { log.error(e.toString()); return false; } }
From source file:iqq.im.service.ApacheHttpService.java
@Override public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener) throws QQException { try {//from w ww. j a va 2s . c o m URI uri = URI.create(request.getUrl()); if (request.getMethod().equals("POST")) { HttpPost httppost = new HttpPost(uri); HttpHost httphost = URIUtils.extractHost(uri); if (httphost == null) { LOG.error("host is null, url: " + uri.toString()); httphost = new HttpHost(uri.getHost()); } if (request.getReadTimeout() > 0) { HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout()); } if (request.getConnectTimeout() > 0) { HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout()); } if (request.getFileMap().size() > 0) { MultipartEntity entity = new MultipartEntity(); String charset = request.getCharset(); Map<String, String> postMap = request.getPostMap(); for (String key : postMap.keySet()) { String value = postMap.get(key); value = value == null ? "" : value; entity.addPart(key, new StringBody(value, Charset.forName(charset))); } Map<String, File> fileMap = request.getFileMap(); for (String key : fileMap.keySet()) { File value = fileMap.get(key); entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value)))); } httppost.setEntity(entity); } else if (request.getPostMap().size() > 0) { List<NameValuePair> list = new ArrayList<NameValuePair>(); Map<String, String> postMap = request.getPostMap(); for (String key : postMap.keySet()) { String value = postMap.get(key); value = value == null ? "" : value; list.add(new BasicNameValuePair(key, value)); } httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset())); } Map<String, String> headerMap = request.getHeaderMap(); for (String key : headerMap.keySet()) { httppost.addHeader(key, headerMap.get(key)); } QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener); QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar); QQHttpResponseCallback callback = new QQHttpResponseCallback(listener); Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback); return new ProxyFuture(future, consumer, producer); } else if (request.getMethod().equals("GET")) { HttpGet httpget = new HttpGet(uri); HttpHost httphost = URIUtils.extractHost(uri); if (httphost == null) { LOG.error("host is null, url: " + uri.toString()); httphost = new HttpHost(uri.getHost()); } Map<String, String> headerMap = request.getHeaderMap(); for (String key : headerMap.keySet()) { httpget.addHeader(key, headerMap.get(key)); } if (request.getReadTimeout() > 0) { HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout()); } if (request.getConnectTimeout() > 0) { HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout()); } return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget), new QQHttpResponseConsumer(request, listener, cookieJar), new QQHttpResponseCallback(listener)); } else { throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod()); } } catch (IOException e) { throw new QQException(QQErrorCode.IO_ERROR); } }
From source file:com.brightcove.com.uploader.helper.MediaManagerHelper.java
public Long uploadFile(URI uri, File f, DefaultHttpClient client) throws HttpException, IOException, URISyntaxException, ParserConfigurationException, SAXException { mLog.info("using " + uri.getHost() + " on port " + uri.getPort() + " for MM upload"); HttpPost method = new HttpPost(uri); MultipartEntity entityIn = new MultipartEntity(); entityIn.addPart("FileName", new StringBody(f.getName(), Charset.forName("UTF-8"))); FileBody fileBody = null;// www . j a va2s.c om if (f != null) { fileBody = new FileBody(f); } if (f != null) { entityIn.addPart(f.getName(), fileBody); } entityIn.addPart("Upload", new StringBody("Submit Query", Charset.forName("UTF-8"))); method.setEntity(entityIn); if (client != null) { return executeUpload(method, client); } return null; }