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:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java
public String doPostMultiData(String url, String method, MobileApplicationBean mobileApplicationBean, String cookie) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Cookie", "JSESSIONID=" + cookie); MultipartEntityBuilder reqEntity;//from w w w.jav a 2s . c o m if (method.equals("upload")) { reqEntity = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(new File(mobileApplicationBean.getApkFile())); reqEntity.addPart("file", fileBody); } else { reqEntity = MultipartEntityBuilder.create(); reqEntity.addPart("version", new StringBody(mobileApplicationBean.getVersion(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("provider", new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("markettype", new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("platform", new StringBody(mobileApplicationBean.getPlatform(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("name", new StringBody(mobileApplicationBean.getName(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("description", new StringBody(mobileApplicationBean.getDescription(), ContentType.MULTIPART_FORM_DATA)); FileBody bannerImageFile = new FileBody(new File(mobileApplicationBean.getBannerFilePath())); reqEntity.addPart("bannerFile", bannerImageFile); FileBody iconImageFile = new FileBody(new File(mobileApplicationBean.getIconFile())); reqEntity.addPart("iconFile", iconImageFile); FileBody screenShot1 = new FileBody(new File(mobileApplicationBean.getScreenShot1File())); reqEntity.addPart("screenshot1File", screenShot1); FileBody screenShot2 = new FileBody(new File(mobileApplicationBean.getScreenShot2File())); reqEntity.addPart("screenshot2File", screenShot2); FileBody screenShot3 = new FileBody(new File(mobileApplicationBean.getScreenShot3File())); reqEntity.addPart("screenshot3File", screenShot3); reqEntity.addPart("addNewAssetButton", new StringBody("Submit", ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("mobileapp", new StringBody(mobileApplicationBean.getMobileapp(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("sso_ssoProvider", new StringBody(mobileApplicationBean.getSso_ssoProvider(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("appmeta", new StringBody(mobileApplicationBean.getAppmeta(), ContentType.MULTIPART_FORM_DATA)); } final HttpEntity entity = reqEntity.build(); httpPost.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(httpPost, responseHandler); if (!method.equals("upload")) { String id_part = responseBody.split(",")[2].split(":")[1]; return id_part.substring(2, (id_part.length() - 2)); } return responseBody; }
From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java
protected HttpEntity getCreateDocumentHttpEntity(File file) { FormBodyPart cmisactionPart = FormBodyPartBuilder .create("cmisaction", new StringBody("createDocument", ContentType.TEXT_PLAIN)).build(); FormBodyPart contentPart = FormBodyPartBuilder .create("content", new FileBody(file, ContentType.TEXT_PLAIN, "testfile.txt")).build(); HttpEntity entity = MultipartEntityBuilder.create().addPart(cmisactionPart) .addTextBody("propertyId[0]", "cmis:name").addTextBody("propertyValue[0]", "testfile01") .addTextBody("propertyId[1]", "cmis:objectTypeId").addTextBody("propertyValue[1]", "File") .addPart(contentPart).build(); return entity; }
From source file:com.ibm.watson.developer_cloud.dialog.v1.DialogService.java
/** * Creates a dialog.// ww w . ja v a 2 s .c o m * * @param name The dialog name * @param dialogFile The dialog file created by using the Dialog service Applet. * @return The created dialog * @see Dialog */ public Dialog createDialog(final String name, final File dialogFile) { if (name == null || name.isEmpty()) throw new IllegalArgumentException("name can not be null or empty"); if (dialogFile == null || !dialogFile.exists()) throw new IllegalArgumentException("dialogFile can not be null or empty"); try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(dialogFile)); reqEntity.addPart("name", new StringBody(name, Charset.forName("UTF-8"))); HttpRequestBase request = Request.Post("/v1/dialogs").withEntity(reqEntity).build(); /*HttpHost proxy=new HttpHost("10.100.1.124",3128); ConnRouteParams.setDefaultProxy(request.getParams(),proxy);*/ HttpResponse response = execute(request); return ResponseUtil.getObject(response, Dialog.class); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.orbeon.oxf.xforms.submission.XFormsSubmissionUtils.java
/** * Implement support for XForms 1.1 section "11.9.7 Serialization as multipart/form-data". * * @param document XML document to submit * @return MultipartRequestEntity *//*from ww w . j av a2 s .c o m*/ public static MultipartEntity createMultipartFormData(final Document document) throws IOException { // Visit document final MultipartEntity multipartEntity = new MultipartEntity(); document.accept(new VisitorSupport() { public final void visit(Element element) { try { // Only care about elements // Only consider leaves i.e. elements without children elements final List children = element.elements(); if (children == null || children.size() == 0) { final String value = element.getText(); { // Got one! final String localName = element.getName(); final QName nodeType = InstanceData.getType(element); if (XMLConstants.XS_ANYURI_QNAME.equals(nodeType)) { // Interpret value as xs:anyURI if (InstanceData.getValid(element) && value.trim().length() > 0) { // Value is valid as per xs:anyURI // Don't close the stream here, as it will get read later when the MultipartEntity // we create here is written to an output stream addPart(multipartEntity, URLFactory.createURL(value).openStream(), element, value); } else { // Value is invalid as per xs:anyURI // Just use the value as is (could also ignore it) multipartEntity.addPart(localName, new StringBody(value, Charset.forName("UTF-8"))); } } else if (XMLConstants.XS_BASE64BINARY_QNAME.equals(nodeType)) { // Interpret value as xs:base64Binary if (InstanceData.getValid(element) && value.trim().length() > 0) { // Value is valid as per xs:base64Binary addPart(multipartEntity, new ByteArrayInputStream(NetUtils.base64StringToByteArray(value)), element, null); } else { // Value is invalid as per xs:base64Binary // Just use the value as is (could also ignore it) multipartEntity.addPart(localName, new StringBody(value, Charset.forName("UTF-8"))); } } else { // Just use the value as is multipartEntity.addPart(localName, new StringBody(value, Charset.forName("UTF-8"))); } } } } catch (IOException e) { throw new OXFException(e); } } }); return multipartEntity; }
From source file:com.ibm.streamsx.topology.internal.context.AnalyticsServiceStreamsContext.java
private BigInteger postJob(CloseableHttpClient httpClient, JSONObject credentials, File bundle, JSONObject submitConfig) throws ClientProtocolException, IOException { String url = getSubmitURL(credentials, bundle); HttpPost postJobWithConfig = new HttpPost(url); postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM); StringBody configBody = new StringBody(submitConfig.serialize(), ContentType.APPLICATION_JSON); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bundleBody) .addPart("json", configBody).build(); postJobWithConfig.setEntity(reqEntity); JSONObject jsonResponse = getJsonResponse(httpClient, postJobWithConfig); Topology.STREAMS_LOGGER.info("Streaming Analytics Service submit job response:" + jsonResponse.serialize()); Object jobId = jsonResponse.get("jobId"); if (jobId == null) return BigInteger.valueOf(-1); return new BigInteger(jobId.toString()); }
From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java
@Override public final <RS> Will<Response<RS>> post(String resource, MultiPartRequest request, Class<RS> clazz) throws RestEndpointIOException { HttpPost post = new HttpPost(spliceUrl(resource)); try {/* w w w . j a v a 2 s .co m*/ MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (MultiPartRequest.MultiPartSerialized<?> serializedPart : request.getSerializedRQs()) { Serializer serializer = getSupportedSerializer(serializedPart); builder.addPart(serializedPart.getPartName(), new StringBody(new String(serializer.serialize(serializedPart.getRequest())), ContentType.parse(serializer.getMimeType()))); } for (MultiPartRequest.MultiPartBinary partBinaty : request.getBinaryRQs()) { builder.addPart(partBinaty.getPartName(), new ByteArrayBody(partBinaty.getData().read(), ContentType.parse(partBinaty.getContentType()), partBinaty.getFilename())); } /* Here is some dirty hack to avoid problem with MultipartEntity and asynchronous http client * Details can be found here: http://comments.gmane.org/gmane.comp.apache.httpclient.user/2426 * * The main idea is to replace MultipartEntity with NByteArrayEntity once first * doesn't support #getContent method * which is required for async client implementation. So, we are copying response * body as byte array to NByteArrayEntity to * leave it unmodified. * * Alse we need to add boundary value to content type header. Details are here: * http://en.wikipedia.org/wiki/Delimiter#Content_boundary * MultipartEntity generates correct header by yourself, but we need to put it * manually once we replaced entity type to NByteArrayEntity */ String boundary = "-------------" + UUID.randomUUID().toString(); builder.setBoundary(boundary); ByteArrayOutputStream baos = new ByteArrayOutputStream(); builder.build().writeTo(baos); post.setEntity(new NByteArrayEntity(baos.toByteArray(), ContentType.MULTIPART_FORM_DATA)); post.setHeader("Content-Type", "multipart/form-data;boundary=" + boundary); } catch (Exception e) { throw new RestEndpointIOException("Unable to build post multipart request", e); } return executeInternal(post, new ClassConverterCallback<RS>(serializers, clazz)); }
From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java
public void createNewApplication(String applicationName, String runtime, String appTypeName, String applicationRevision, String applicationDescription, String uploadedFileName, String runtimeProperties, String tags, File uploadArtifact, boolean isNewVersion, String applicationContext, String conSpec, boolean setDefaultVersion, String appCreationMethod, String gitRepoUrl, String gitRepoBranch, String projectRoot) throws AppCloudIntegrationTestException { HttpClient httpclient = null;/*from w w w. j av a 2 s . c o m*/ org.apache.http.HttpResponse response = null; int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod(); try { httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httppost = new HttpPost(this.endpoint); httppost.setConfig(requestConfig); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(PARAM_NAME_ACTION, new StringBody(CREATE_APPLICATION_ACTION, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APP_CREATION_METHOD, new StringBody(appCreationMethod, ContentType.TEXT_PLAIN)); if (GITHUB.equals(appCreationMethod)) { builder.addPart(PARAM_NAME_GIT_REPO_URL, new StringBody(gitRepoUrl, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_GIT_REPO_BRANCH, new StringBody(gitRepoBranch, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_PROJECT_ROOT, new StringBody(projectRoot, ContentType.TEXT_PLAIN)); } else if (DEFAULT.equals(appCreationMethod)) { builder.addPart(PARAM_NAME_FILE_UPLOAD, new FileBody(uploadArtifact)); builder.addPart(PARAM_NAME_UPLOADED_FILE_NAME, new StringBody(uploadedFileName, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_IS_FILE_ATTACHED, new StringBody(Boolean.TRUE.toString(), ContentType.TEXT_PLAIN));//Setting true to send the file in request } builder.addPart(PARAM_NAME_CONTAINER_SPEC, new StringBody(conSpec, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_NAME, new StringBody(applicationName, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_DESCRIPTION, new StringBody(applicationDescription, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_RUNTIME, new StringBody(runtime, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APP_TYPE_NAME, new StringBody(appTypeName, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APP_CONTEXT, new StringBody(applicationContext, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_REVISION, new StringBody(applicationRevision, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_PROPERTIES, new StringBody(runtimeProperties, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_TAGS, new StringBody(tags, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_IS_NEW_VERSION, new StringBody(Boolean.toString(isNewVersion), ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_SET_DEFAULT_VERSION, new StringBody(Boolean.toString(setDefaultVersion), ContentType.TEXT_PLAIN)); httppost.setEntity(builder.build()); httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE)); response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity()); throw new AppCloudIntegrationTestException("CreateNewApplication failed " + result); } } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) { // In most of the cases, even though connection is timed out, actual activity is completed. // If application is not created, in next test case, it will be identified. log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1); } catch (IOException e) { log.error("Failed to invoke application creation API.", e); throw new AppCloudIntegrationTestException("Failed to invoke application creation API.", e); } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(httpclient); } }
From source file:org.hlc.http.resetfull.network.HttpExecutor.java
/** * Do post./*w w w .jav a2 s . c om*/ * * @param <E> the element type * @param url the url * @param paramter the paramter * @param files the files * @param readTimeout the read timeout * @param result the result * @return the e */ public <E> E doPost(String url, Map<String, Object> paramter, Map<String, File> files, int readTimeout, MessageResolve<E> result) { MultipartEntity multipartEntity = new MultipartEntity(); try { if (paramter != null) { for (String name : paramter.keySet()) { multipartEntity.addPart(name, new StringBody(String.valueOf(paramter.get(name)), Charset.forName(HTTP.UTF_8))); } } if (files != null) { for (String name : files.keySet()) { multipartEntity.addPart(name, new FileBody(files.get(name))); } } } catch (Exception e) { Log.debug(e.getMessage()); result.error(NETWORK_ERROR, DEFUALT_MESSAGE_TYPE, e.getMessage()); return null; } HttpPost httpPost = new HttpPost(url); httpPost.setEntity(multipartEntity); return doExecute(httpPost, readTimeout, result); }
From source file:com.gistlabs.mechanize.requestor.RequestBuilder.java
private HttpPost composeMultiPartFormRequest(final String uri, final Parameters parameters, final Map<String, ContentBody> files) { HttpPost request = new HttpPost(uri); MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try {//from w ww . jav a 2 s . c om Charset utf8 = Charset.forName("UTF-8"); for (Parameter param : parameters) if (param.isSingleValue()) multiPartEntity.addPart(param.getName(), new StringBody(param.getValue(), utf8)); else for (String value : param.getValues()) multiPartEntity.addPart(param.getName(), new StringBody(value, utf8)); } catch (UnsupportedEncodingException e) { throw MechanizeExceptionFactory.newException(e); } List<String> fileNames = new ArrayList<String>(files.keySet()); Collections.sort(fileNames); for (String name : fileNames) { ContentBody contentBody = files.get(name); multiPartEntity.addPart(name, contentBody); } request.setEntity(multiPartEntity); return request; }
From source file:org.apache.manifoldcf.agents.output.solr.ModifiedHttpSolrServer.java
@Override public NamedList<Object> request(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpRequestBase method = null;//from www. j av a2 s .c o 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); } 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 + toQueryString(params, 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; LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url); 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<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 (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 = "application/octet-stream"; // default } String contentName = content.getName(); parts.add(new FormBodyPart(contentName, new InputStreamBody(content.getStream(), contentType, content.getName()))); } } if (parts.size() > 0) { ModifiedMultipartEntity entity = new ModifiedMultipartEntity( HttpMultipartMode.STRICT, null, StandardCharsets.UTF_8); 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 = 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); } // XXX client already has this set, is this needed? //method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, // followRedirects); method.addHeader("User-Agent", AGENT); InputStream respBody = null; boolean shouldClose = true; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents respBody = response.getEntity().getContent(); // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_CONFLICT: // 409 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; default: throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase()); } if (processor == null) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<Object>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; return rsp; } Charset charsetObject = ContentType.getOrDefault(response.getEntity()).getCharset(); String charset; if (charsetObject != null) charset = charsetObject.name(); else charset = "utf-8"; 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 = URLDecoder.decode(msg.toString()); } 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 && shouldClose) { try { respBody.close(); } catch (Throwable t) { } // ignore } } }