List of usage examples for org.apache.http.entity.mime.content InputStreamBody InputStreamBody
public InputStreamBody(final InputStream in, final String filename)
From source file:com.indigenedroid.app.volley.tools.MultiPartRequest.java
@Override public byte[] getBody() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); mEntity = new MultipartEntity(); FileInputStream fis;/*from w w w . ja v a 2 s. c om*/ try { fis = new FileInputStream(fileUploads.get("portrait_file")); InputStreamBody body = new InputStreamBody(fis, getFileName(fileUploads.get("portrait_file").getAbsolutePath())); mEntity.addPart("portrait_file", body); try { mEntity.addPart("token", new StringBody(stringUploads.get("token"))); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //HttpEntity entity = new FileEntity(fileUploads.get("portrait_file"), "application/octet-stream"); try { mEntity.writeTo(bos); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bos.toByteArray(); //return super.getBody(); }
From source file:com.parworks.androidlibrary.ar.ARSites.java
/** * Synchronously augment an image towards a list of sites * // ww w .j a v a 2s . co m * @param image * an inputstream containing the image * @return the augmented data */ public AugmentedData augmentImageGroup(List<String> sites, InputStream image) { Map<String, String> params = new HashMap<String, String>(); MultipartEntity imageEntity = new MultipartEntity(); InputStreamBody imageInputStreamBody = new InputStreamBody(image, "image"); imageEntity.addPart("image", imageInputStreamBody); for (String siteId : sites) { try { imageEntity.addPart("site", new StringBody(siteId)); } catch (UnsupportedEncodingException e) { throw new ARException(e); } } HttpUtils httpUtils = new HttpUtils(mApiKey, mTime, mSignature); HttpResponse serverResponse = httpUtils .doPost(HttpUtils.PARWORKS_API_BASE_URL + HttpUtils.AUGMENT_IMAGE_GROUP_PATH, imageEntity, params); HttpUtils.handleStatusCode(serverResponse.getStatusLine().getStatusCode()); ARResponseHandler responseHandler = new ARResponseHandlerImpl(); AugmentImageGroupResponse augmentImageGroupResponse = responseHandler.handleResponse(serverResponse, AugmentImageGroupResponse.class); if (augmentImageGroupResponse.getSuccess() == false) { throw new ARException( "Successfully communicated with the server, failed to augment the image. Perhaps the site does not exist or has no overlays."); } // List<AugmentedData> result = new ArrayList<AugmentedData>(); // for(SiteImageBundle bundle : augmentImageGroupResponse.getCandidates()) { // AugmentedData augmentedImage = null; // while (augmentedImage == null) { // augmentedImage = getAugmentResult(bundle.getSite(), bundle.getImgId()); // } // result.add(augmentedImage); // } List<AugmentedData> result = getAugmentedImageGroupResult(augmentImageGroupResponse.getSitesToCheck(), augmentImageGroupResponse.getImgId()); // combine different results AugmentedData finalData = null; for (AugmentedData data : result) { if (data.isLocalization()) { if (finalData == null) { finalData = data; } else { finalData.getOverlays().addAll(data.getOverlays()); } } } return finalData; }
From source file:com.diversityarrays.dalclient.httpimpl.DalHttpFactoryImpl.java
@Override public DalRequest createForUpload(String url, List<Pair<String, String>> pairs, String rand_num, String namesInOrder, String signature, Factory<InputStream> factory) { MultipartEntityBuilder builder = MultipartEntityBuilder.create() .addPart("uploadfile", new InputStreamBody(factory.create(), "uploadfile")) .addTextBody("rand_num", rand_num).addTextBody("url", url); for (Pair<String, String> pair : pairs) { builder.addTextBody(pair.a, pair.b); }/*w w w .j a v a2s . co m*/ HttpEntity entity = builder.addTextBody("param_order", namesInOrder).addTextBody("signature", signature) .build(); HttpPost post = new HttpPost(url); post.setEntity(entity); return new DalRequestImpl(post); }
From source file:com.liferay.arquillian.container.LiferayContainer.java
private MultipartEntity createMultipartEntity(Archive<?> archive) { ZipExporter zipView = archive.as(ZipExporter.class); InputStream inputStream = zipView.exportAsInputStream(); MultipartEntity entity = new MultipartEntity(); entity.addPart(archive.getName(), new InputStreamBody(inputStream, archive.getName())); return entity; }
From source file:interactivespaces.util.web.HttpClientHttpContentCopier.java
@Override public void copyTo(String destinationUri, InputStream source, String sourceFileName, String sourceParameterName, Map<String, String> params) { InputStreamBody contentBody = new InputStreamBody(source, sourceFileName); doCopyTo(destinationUri, sourceParameterName, params, contentBody); }
From source file:jp.tonyu.soytext2.file.Comm.java
public Scriptable execMultiPart(String rootPath, String relPath, final Scriptable sparams, Object responseType) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(rootPath + relPath); final MultipartEntity reqEntity = new MultipartEntity(); Scriptables.each(sparams, new StringPropAction() { @Override/*from w w w .j a v a 2 s . c om*/ public void run(String key, Object value) { if (value instanceof String) { String s = (String) value; try { reqEntity.addPart(key, new StringBody(s, Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else if (value instanceof Scriptable) { Scriptable s = (Scriptable) value; String filename = (String) ScriptableObject.getProperty(s, FileUpload.FILENAME); Object body = ScriptableObject.getProperty(s, FileUpload.BODY); InputStream st = null; if (body instanceof InputStream) { st = (InputStream) body; } else if (body instanceof ReadableBinData) { ReadableBinData rbd = (ReadableBinData) body; try { st = rbd.getInputStream(); } catch (IOException e) { Log.die(e); } } if (st == null) throw new RuntimeException("Not a bindata - " + body); InputStreamBody bin = new InputStreamBody(st, filename); reqEntity.addPart(key, bin); } } }); httppost.setEntity(reqEntity); Log.d(this, "executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); Scriptable res = response2Scriptable(response, responseType); return res; }
From source file:com.janoz.usenet.processors.impl.WebbasedProcessor.java
@Override public void processNZB(NZB nzb) throws RetrieveException { try {//from www .j a v a2 s .c o m login(); List<NameValuePair> fields = null; String command = null; if (useReportId(nzb)) { fields = getReportIdProps(nzb); command = getReportIdCommand(); } else if (useUrl(nzb)) { fields = getUrlProps(nzb); command = getUrlCommand(); } if (fields != null) { //Do the request HttpResponse response = null; try { response = doGet(command, fields); validateResponse(response.getEntity().getContent()); } finally { if (response != null) { response.getEntity().consumeContent(); } } } else { // no url or reportId //post file using POST fields = getFilepostOtherProps(nzb); command = getFilepostCommand(); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cb = new InputStreamBody(new ByteArrayInputStream(nzb.getData()), nzb.getFilename()); entity.addPart(getFilepostField(), cb); HttpResponse response = null; try { response = doPost(command, fields, entity); validateResponse(response.getEntity().getContent()); } finally { if (response != null) { response.getEntity().consumeContent(); } } } logout(); } catch (IOException e) { throw new RetrieveException("Error posting nzb file", e); } }
From source file:org.codegist.crest.HttpClientRestService.java
private static HttpUriRequest toHttpUriRequest(HttpRequest request) throws UnsupportedEncodingException { HttpUriRequest uriRequest;//ww w. ja v a 2 s. com String queryString = ""; if (request.getQueryParams() != null) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : request.getQueryParams().entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } String qs = URLEncodedUtils.format(params, request.getEncoding()); queryString = Strings.isNotBlank(qs) ? ("?" + qs) : ""; } String uri = request.getUri().toString() + queryString; switch (request.getMeth()) { default: case GET: uriRequest = new HttpGet(uri); break; case POST: uriRequest = new HttpPost(uri); break; case PUT: uriRequest = new HttpPut(uri); break; case DELETE: uriRequest = new HttpDelete(uri); break; case HEAD: uriRequest = new HttpHead(uri); break; } if (uriRequest instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase enclosingRequestBase = ((HttpEntityEnclosingRequestBase) uriRequest); HttpEntity entity; if (Params.isForUpload(request.getBodyParams().values())) { MultipartEntity multipartEntity = new MultipartEntity(); for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) { ContentBody body; if (param.getValue() instanceof InputStream) { body = new InputStreamBody((InputStream) param.getValue(), param.getKey()); } else if (param.getValue() instanceof File) { body = new FileBody((File) param.getValue()); } else if (param.getValue() != null) { body = new StringBody(param.getValue().toString(), request.getEncodingAsCharset()); } else { body = new StringBody(null); } multipartEntity.addPart(param.getKey(), body); } entity = multipartEntity; } else { List<NameValuePair> params = new ArrayList<NameValuePair>(request.getBodyParams().size()); for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) { params.add(new BasicNameValuePair(param.getKey(), param.getValue() != null ? param.getValue().toString() : null)); } entity = new UrlEncodedFormEntity(params, request.getEncoding()); } enclosingRequestBase.setEntity(entity); } if (request.getHeaders() != null && !request.getHeaders().isEmpty()) { for (Map.Entry<String, String> header : request.getHeaders().entrySet()) { uriRequest.setHeader(header.getKey(), header.getValue()); } } if (request.getConnectionTimeout() != null && request.getConnectionTimeout() >= 0) { HttpConnectionParams.setConnectionTimeout(uriRequest.getParams(), request.getConnectionTimeout().intValue()); } if (request.getSocketTimeout() != null && request.getSocketTimeout() >= 0) { HttpConnectionParams.setSoTimeout(uriRequest.getParams(), request.getSocketTimeout().intValue()); } return uriRequest; }
From source file:org.bimserver.client.Channel.java
public long checkin(String baseAddress, String token, long poid, String comment, long deserializerOid, boolean merge, boolean sync, long fileSize, String filename, InputStream inputStream) throws ServerException, UserException { String address = baseAddress + "/upload"; DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); }//w w w .ja va2 s . c o m } }); httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); HttpPost httppost = new HttpPost(address); try { // TODO find some GzipInputStream variant that _compresses_ instead of _decompresses_ using deflate for now InputStreamBody data = new InputStreamBody(new DeflaterInputStream(inputStream), filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("data", data); reqEntity.addPart("token", new StringBody(token)); reqEntity.addPart("deserializerOid", new StringBody("" + deserializerOid)); reqEntity.addPart("merge", new StringBody("" + merge)); reqEntity.addPart("poid", new StringBody("" + poid)); reqEntity.addPart("comment", new StringBody("" + comment)); reqEntity.addPart("sync", new StringBody("" + sync)); reqEntity.addPart("compression", new StringBody("deflate")); httppost.setEntity(reqEntity); HttpResponse httpResponse = httpclient.execute(httppost); if (httpResponse.getStatusLine().getStatusCode() == 200) { JsonParser jsonParser = new JsonParser(); JsonElement result = jsonParser .parse(new JsonReader(new InputStreamReader(httpResponse.getEntity().getContent()))); if (result instanceof JsonObject) { JsonObject jsonObject = (JsonObject) result; if (jsonObject.has("exception")) { JsonObject exceptionJson = jsonObject.get("exception").getAsJsonObject(); String exceptionType = exceptionJson.get("__type").getAsString(); String message = exceptionJson.has("message") ? exceptionJson.get("message").getAsString() : "unknown"; if (exceptionType.equals(UserException.class.getSimpleName())) { throw new UserException(message); } else if (exceptionType.equals(ServerException.class.getSimpleName())) { throw new ServerException(message); } } else { return jsonObject.get("checkinid").getAsLong(); } } } } catch (ClientProtocolException e) { LOGGER.error("", e); } catch (IOException e) { LOGGER.error("", e); } return -1; }