List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create
public static MultipartEntityBuilder create()
From source file:edu.mit.scratch.Scratch.java
public static ScratchSession register(final String username, final String password, final String gender, final int birthMonth, final String birthYear, final String country, final String email) throws ScratchUserException { // Long if statement to verify all fields are valid if ((username.length() < 3) || (username.length() > 20) || (password.length() < 6) || (gender.length() < 2) || (birthMonth < 1) || (birthMonth > 12) || (birthYear.length() != 4) || (country.length() == 0) || (email.length() < 5)) { throw new ScratchUserException(); // TDL: Specify reason for failure } else {/*from w w w . java 2 s . c o m*/ try { final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(lang); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/") .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu") .addHeader("X-Requested-With", "XMLHttpRequest").build(); try { resp = httpClient.execute(csrf); } catch (final IOException e) { e.printStackTrace(); throw new ScratchUserException(); } try { resp.close(); } catch (final IOException e) { throw new ScratchUserException(); } String csrfToken = null; for (final Cookie c : cookieStore.getCookies()) if (c.getName().equals("scratchcsrftoken")) csrfToken = c.getValue(); /* * try { * username = URLEncoder.encode(username, "UTF-8"); * password = URLEncoder.encode(password, "UTF-8"); * birthMonth = Integer.parseInt(URLEncoder.encode("" + * birthMonth, "UTF-8")); * birthYear = URLEncoder.encode(birthYear, "UTF-8"); * gender = URLEncoder.encode(gender, "UTF-8"); * country = URLEncoder.encode(country, "UTF-8"); * email = URLEncoder.encode(email, "UTF-8"); * } catch (UnsupportedEncodingException e1) { * e1.printStackTrace(); * } */ final BasicClientCookie csrfCookie = new BasicClientCookie("scratchcsrftoken", csrfToken); csrfCookie.setDomain(".scratch.mit.edu"); csrfCookie.setPath("/"); cookieStore.addCookie(csrfCookie); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(debug); httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); /* * final String data = "username=" + username + "&password=" + * password + "&birth_month=" + birthMonth + "&birth_year=" + * birthYear + "&gender=" + gender + "&country=" + country + * "&email=" + email + * "&is_robot=false&should_generate_admin_ticket=false&usernames_and_messages=%3Ctable+class%3D'banhistory'%3E%0A++++%3Cthead%3E%0A++++++++%3Ctr%3E%0A++++++++++++%3Ctd%3EAccount%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EEmail%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EReason%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EDate%3C%2Ftd%3E%0A++++++++%3C%2Ftr%3E%0A++++%3C%2Fthead%3E%0A++++%0A%3C%2Ftable%3E%0A&csrfmiddlewaretoken=" * + csrfToken; * System.out.println(data); */ final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("birth_month", birthMonth + "", ContentType.TEXT_PLAIN); builder.addTextBody("birth_year", birthYear, ContentType.TEXT_PLAIN); builder.addTextBody("country", country, ContentType.TEXT_PLAIN); builder.addTextBody("csrfmiddlewaretoken", csrfToken, ContentType.TEXT_PLAIN); builder.addTextBody("email", email, ContentType.TEXT_PLAIN); builder.addTextBody("gender", gender, ContentType.TEXT_PLAIN); builder.addTextBody("is_robot", "false", ContentType.TEXT_PLAIN); builder.addTextBody("password", password, ContentType.TEXT_PLAIN); builder.addTextBody("should_generate_admin_ticket", "false", ContentType.TEXT_PLAIN); builder.addTextBody("username", username, ContentType.TEXT_PLAIN); builder.addTextBody("usernames_and_messages", "<table class=\"banhistory\"> <thead> <tr> <td>Account</td> <td>Email</td> <td>Reason</td> <td>Date</td> </tr> </thead> </table>", ContentType.TEXT_PLAIN); final HttpUriRequest createAccount = RequestBuilder.post() .setUri("https://scratch.mit.edu/accounts/register_new_user/") .addHeader("Accept", "application/json, text/javascript, */*; q=0.01") .addHeader("Referer", "https://scratch.mit.edu/accounts/standalone-registration/") .addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate").addHeader("DNT", "1") .addHeader("Accept-Language", "en-US,en;q=0.8") .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") .addHeader("X-Requested-With", "XMLHttpRequest").addHeader("X-CSRFToken", csrfToken) .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id", "54255D9A-9771-4CAC-9052-50C8AB7469E0") .setEntity(builder.build()).build(); resp = httpClient.execute(createAccount); System.out.println("REGISTER:" + resp.getStatusLine()); final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); System.out.println("exact:" + result.toString() + "\n" + resp.getStatusLine().getReasonPhrase() + "\n" + resp.getStatusLine()); if (resp.getStatusLine().getStatusCode() != 200) throw new ScratchUserException(); resp.close(); } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } try { return Scratch.createSession(username, password); } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } } }
From source file:nzilbb.bas.BAS.java
/** * Invokes the MAUSBasic service, which combines G2P and MAUS for forced alignment given a WAV file and a plain text orthrogaphic transcript. * @param LANGUAGE <a href="https://tools.ietf.org/html/rfc5646">RFC 5646</a> tag for identifying the language. * @param SIGNAL The signal, in WAV format. * @param TEXT The transcription of the text. * @return The result of the call./*from w w w .jav a 2 s. co m*/ * @throws IOException If an IO error occurs. * @throws ParserConfigurationException If the XML parser for parsing the response could not be configured. */ public BASResponse MAUSBasic(String LANGUAGE, InputStream SIGNAL, InputStream TEXT) throws IOException, ParserConfigurationException { HttpPost request = new HttpPost(getMAUSBasicUrl()); HttpEntity entity = MultipartEntityBuilder.create().addTextBody("LANGUAGE", languageTagger.tag(LANGUAGE)) .addBinaryBody("SIGNAL", SIGNAL, ContentType.create("audio/wav"), "BAS.wav") .addBinaryBody("TEXT", TEXT, ContentType.create("text/plain"), "BAS.txt").build(); request.setEntity(entity); HttpResponse httpResponse = httpclient.execute(request); HttpEntity result = httpResponse.getEntity(); return new BASResponse(result.getContent()); }
From source file:com.wudaosoft.net.httpclient.Request.java
/** * // www . j a v a 2 s . co m * @param workerBuilder * @param responseHandler * @return * @throws Exception */ public <T> T doRequest(WorkerBuilder workerBuilder, ResponseHandler<T> responseHandler) throws Exception { String method = workerBuilder.getMethod(); String url = workerBuilder.getUrl(); Args.notNull(workerBuilder, "WorkerBuilder"); Args.notEmpty(method, "WorkerBuilder.getMethod()"); Args.notEmpty(url, "WorkerBuilder.getUrl()"); Args.notNull(responseHandler, "responseHandler"); // if(!workerBuilder.isAnyHost()) { if (!isFullUrl(url)) { // notFullUrl(url); Args.notEmpty(hostConfig.getHostUrl(), "HostConfig.getHostUrl()"); url = hostConfig.getHostUrl() + url; } Charset charset = hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset(); String stringBody = workerBuilder.getStringBody(); File fileBody = workerBuilder.getFileBody(); InputStream streamBody = workerBuilder.getStreamBody(); Map<String, String> params = workerBuilder.getParameters(); String contentType = null; if (responseHandler instanceof JsonResponseHandler) { contentType = MediaType.APPLICATION_JSON_VALUE; } else if (responseHandler instanceof SAXSourceResponseHandler || responseHandler instanceof XmlResponseHandler) { contentType = MediaType.APPLICATION_XML_VALUE; } else if (responseHandler instanceof FileResponseHandler || responseHandler instanceof ImageResponseHandler || responseHandler instanceof OutputStreamResponseHandler) { contentType = MediaType.ALL_VALUE; } else if (responseHandler instanceof NoResultResponseHandler) { contentType = ((NoResultResponseHandler) responseHandler).getContentType().getMimeType(); } else { contentType = MediaType.TEXT_PLAIN_VALUE; } RequestBuilder requestBuilder = RequestBuilder.create(method).setCharset(charset).setUri(url); if (stringBody != null) { StringEntity reqEntity = new StringEntity(stringBody, charset); reqEntity.setContentType(contentType + ";charset=" + charset.name()); requestBuilder.setEntity(reqEntity); } else if (fileBody != null || streamBody != null) { String filename = workerBuilder.getFilename(); MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create().setLaxMode(); if (fileBody != null) { Args.check(fileBody.isFile(), "fileBody must be a file"); Args.check(fileBody.canRead(), "fileBody must be readable"); if (filename == null && streamBody == null) filename = fileBody.getName(); FileBody bin = new FileBody(fileBody, ContentType.APPLICATION_OCTET_STREAM, streamBody != null ? fileBody.getName() : filename); reqEntity.addPart(workerBuilder.getFileFieldName(), bin); } Args.notEmpty(filename, "filename"); if (streamBody != null) reqEntity.addBinaryBody(workerBuilder.getFileFieldName(), streamBody, ContentType.APPLICATION_OCTET_STREAM, filename); buildParameters(reqEntity, params, charset); requestBuilder.setEntity(reqEntity.build()); } if (fileBody == null && streamBody == null) { buildParameters(requestBuilder, params); } if (workerBuilder.getReadTimeout() > -1) { requestBuilder.setConfig(RequestConfig.copy(this.hostConfig.getRequestConfig()) .setSocketTimeout(workerBuilder.getReadTimeout()).build()); } HttpUriRequest httpRequest = ParameterRequestBuilder.build(requestBuilder); setAcceptHeader(httpRequest, contentType); if (workerBuilder.isAjax()) setAjaxHeader(httpRequest); HttpClientContext context = workerBuilder.getContext(); if (context == null) context = defaultHttpContext; T result = getHttpClient().execute(httpRequest, responseHandler, context); if (log.isDebugEnabled()) { log.debug(String.format("Send data to path:[%s]\"%s\". result: %s", method, url, result)); } return result; }
From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java
/** * Upload a sample datatset from resources * //from w w w . ja v a2s. co m * @param datasetName Name for the dataset * @param version Version for the dataset * @param tableName Relative path the CSV file in resources * @return Response from the backend * @throws MLHttpClientException */ public CloseableHttpResponse uploadDatasetFromDAS(String datasetName, String version, String tableName) throws MLHttpClientException { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/datasets/"); httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey()); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addPart("description", new StringBody("Sample dataset for Testing", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("sourceType", new StringBody("das", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("destination", new StringBody("file", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("sourcePath", new StringBody(tableName, ContentType.TEXT_PLAIN)); if (datasetName != null) { multipartEntityBuilder.addPart("datasetName", new StringBody(datasetName, ContentType.TEXT_PLAIN)); } if (version != null) { multipartEntityBuilder.addPart("version", new StringBody(version, ContentType.TEXT_PLAIN)); } multipartEntityBuilder.addBinaryBody("file", new byte[] {}, ContentType.APPLICATION_OCTET_STREAM, "IndiansDiabetes.csv"); httpPost.setEntity(multipartEntityBuilder.build()); return httpClient.execute(httpPost); } catch (Exception e) { throw new MLHttpClientException("Failed to upload dataset from DAS " + tableName, e); } }
From source file:com.osbitools.ws.shared.web.BasicWebUtils.java
public WebResponse uploadFile(String path, String fname, InputStream in, String stoken) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(path); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA); builder.addPart("fname", fn); builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname); BasicCookieStore cookieStore = new BasicCookieStore(); if (stoken != null) { BasicClientCookie cookie = new BasicClientCookie(Constants.SECURE_TOKEN_NAME, stoken); cookie.setDomain(TestConstants.JETTY_HOST); cookie.setPath("/"); cookieStore.addCookie(cookie);/*www . j a v a 2s . c o m*/ } TestConstants.LOG.debug("stoken=" + stoken); HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse response = client.execute(post); String body; ResponseHandler<String> handler = new BasicResponseHandler(); try { body = handler.handleResponse(response); } catch (HttpResponseException e) { return new WebResponse(e.getStatusCode(), e.getMessage()); } return new WebResponse(response.getStatusLine().getStatusCode(), body); }
From source file:io.swagger.client.api.DefaultApi.java
/** * Movie sync availability/*w w w. j a v a2 s . co m*/ * Checks whether a list of client movie identifiers (Video On Demand) are available to be synchronized using the Dive API * @param authorization Authorization token ('Bearer <token>') * @param clientMovieIdList List of client movie IDs, provided as a comma separated list * @param acceptLanguage Client locale, as <language>-<country> * @param contentType application/json * @return List<MovieStatus> */ public List<MovieStatus> getReadyMovies(String authorization, List<String> clientMovieIdList, String acceptLanguage, String contentType) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'authorization' is set if (authorization == null) { throw new ApiException(400, "Missing the required parameter 'authorization' when calling getReadyMovies"); } // verify the required parameter 'clientMovieIdList' is set if (clientMovieIdList == null) { throw new ApiException(400, "Missing the required parameter 'clientMovieIdList' when calling getReadyMovies"); } // create path and map variables String localVarPath = "/movies/{client_movie_id_list}/ready".replaceAll("\\{format\\}", "json").replaceAll( "\\{" + "client_movie_id_list" + "\\}", apiInvoker.escapeString(clientMovieIdList.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); // header params Map<String, String> localVarHeaderParams = new HashMap<String, String>(); // form params Map<String, String> localVarFormParams = new HashMap<String, String>(); localVarHeaderParams.put("Authorization", ApiInvoker.parameterToString(authorization)); localVarHeaderParams.put("Accept-Language", ApiInvoker.parameterToString(acceptLanguage)); localVarHeaderParams.put("Content-Type", ApiInvoker.parameterToString(contentType)); String[] localVarContentTypes = { "application/json" }; String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; if (localVarContentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); localVarPostBody = localVarBuilder.build(); } else { // normal form params } try { String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); if (localVarResponse != null) { return (List<MovieStatus>) ApiInvoker.deserialize(localVarResponse, "array", MovieStatus.class); } else { return null; } } catch (ApiException ex) { throw ex; } }
From source file:org.biouno.figshare.FigShareClient.java
/** * Upload a file to an article./* ww w . ja v a 2s .com*/ * * @param articleId article ID * @param file java.io.File file * @return org.biouno.figshare.v1.model.File uploaded file, without the thumbnail URL */ public org.biouno.figshare.v1.model.File uploadFile(long articleId, File file) { HttpClient httpClient = null; try { final String method = String.format("my_data/articles/%d/files", articleId); // create an HTTP request to a protected resource final String url = getURL(endpoint, version, method); // create an HTTP request to a protected resource final HttpPut request = new HttpPut(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ContentBody body = new FileBody(file); FormBodyPart part = FormBodyPartBuilder.create("filedata", body).build(); builder.addPart(part); HttpEntity entity = builder.build(); request.setEntity(entity); // sign the request consumer.sign(request); // send the request httpClient = HttpClientBuilder.create().build(); HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); String json = EntityUtils.toString(responseEntity); org.biouno.figshare.v1.model.File uploadedFile = readFileFromJson(json); return uploadedFile; } catch (OAuthCommunicationException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (OAuthMessageSignerException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (OAuthExpectationFailedException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (ClientProtocolException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (IOException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } }
From source file:com.secdec.codedx.api.client.CodeDxClient.java
/** * Kicks off a CodeDx analysis run on a specified project * * @return A StartAnalysisResponse object * @param projectId The project ID/*from w ww.ja v a2s . co m*/ * @param artifacts An array of streams to send over as analysis artifacts * @throws ClientProtocolException * @throws IOException * @throws CodeDxClientException * */ public StartAnalysisResponse startAnalysis(int projectId, InputStream[] artifacts) throws ClientProtocolException, IOException, CodeDxClientException { HttpPost postRequest = new HttpPost(url + "projects/" + projectId + "/analysis"); postRequest.addHeader(KEY_HEADER, key); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (InputStream artifact : artifacts) { builder.addPart("file[]", new InputStreamBody(artifact, "file[]")); } HttpEntity entity = builder.build(); postRequest.setEntity(entity); HttpResponse response = httpClient.execute(postRequest); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 202) { throw new CodeDxClientException( "Failed to start analysis. " + IOUtils.toString(response.getEntity().getContent()), responseCode); } String data = IOUtils.toString(response.getEntity().getContent()); return gson.<StartAnalysisResponse>fromJson(data, new TypeToken<StartAnalysisResponse>() { }.getType()); }
From source file:jp.realglobe.util.uploader.DirectoryUploader.java
/** * ?/*from www .j a va 2s .co m*/ * @param token1 ? * @param path ?? * @throws IOException ???????? * @throws HttpException HTTP */ private void upload(final String token1, final Path path) throws HttpException, IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { final HttpPost post = new HttpPost(this.uploadUrl); post.setEntity(MultipartEntityBuilder.create().addTextBody("info", "{}") .addTextBody(Constants.UPLOAD_REQUEST_PART_TOKEN, token1) .addBinaryBody(Constants.UPLOAD_REQUEST_PART_DATA, path.toFile()).build()); LOG.info("Upload " + path); try (CloseableHttpResponse response = client.execute(post)) { if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) { return; } LOG.warning(response.toString()); } } }
From source file:io.swagger.client.api.CameraApi.java
/** * Capture a photo//from w w w. j ava2 s . c o m * */ public void capturePhotoPost(final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) { Object postBody = null; // create path and map variables String path = "/capture/photo".replaceAll("\\{format\\}", "json"); // query params List<Pair> queryParams = new ArrayList<Pair>(); // header params Map<String, String> headerParams = new HashMap<String, String>(); // form params Map<String, String> formParams = new HashMap<String, String>(); String[] contentTypes = { }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; } else { // normal form params } String[] authNames = new String[] {}; try { apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames, new Response.Listener<String>() { @Override public void onResponse(String localVarResponse) { responseListener.onResponse(localVarResponse); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { errorListener.onErrorResponse(error); } }); } catch (ApiException ex) { errorListener.onErrorResponse(new VolleyError(ex)); } }