/** * Compress data to send to server. * Creates a Http Entity holding the gzipped data. * The data will not be compressed if it is too short. * @param data The bytes to compress * @return Entity holding the data */ public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver) throws IOException { AbstractHttpEntity entity; if (data.length < getMinGzipSize(resolver)) { entity = new ByteArrayEntity(data); } else { ByteArrayOutputStream arr = new ByteArrayOutputStream(); OutputStream zipper = new GZIPOutputStream(arr); zipper.write(data); zipper.close(); entity = new ByteArrayEntity(arr.toByteArray()); entity.setContentEncoding("gzip"); } return entity; }
private String sendPost(String url, AbstractHttpEntity body, HashMap<String, String> headers) throws ClientProtocolException, IOException { throttle(); HttpPost postRequest = new HttpPost(url); if (headers != null) { for (Entry<String, String> e : headers.entrySet()) { postRequest.addHeader(e.getKey(), e.getValue()); } } postRequest.setEntity(body); CloseableHttpResponse closeableHttpResponse = HttpClients.createDefault().execute(postRequest); String response = Helpers.convertInputStreamToString(closeableHttpResponse.getEntity().getContent()); return response; }
/** * Compress data to send to server. * Creates a Http Entity holding the gzipped data. * The data will not be compressed if it is too short. * * @param data The bytes to compress * @return Entity holding the data */ public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver) throws IOException { AbstractHttpEntity entity; if (data.length < getMinGzipSize(resolver)) { entity = new ByteArrayEntity(data); } else { ByteArrayOutputStream arr = new ByteArrayOutputStream(); OutputStream zipper = new GZIPOutputStream(arr); zipper.write(data); zipper.close(); entity = new ByteArrayEntity(arr.toByteArray()); entity.setContentEncoding("gzip"); } return entity; }
/** * Compress data to send to server. Creates a Http Entity holding the * gzipped data. The data will not be compressed if it is too short. * * @param data The bytes to compress * @return Entity holding the data */ public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver) throws IOException { AbstractHttpEntity entity; if (data.length < getMinGzipSize(resolver)) { entity = new ByteArrayEntity(data); } else { ByteArrayOutputStream arr = new ByteArrayOutputStream(); OutputStream zipper = new GZIPOutputStream(arr); zipper.write(data); zipper.close(); entity = new ByteArrayEntity(arr.toByteArray()); entity.setContentEncoding("gzip"); } return entity; }
@Override public boolean insert(Page page) { TargetModelElasticSearch document = new TargetModelElasticSearch(page); String docId = encodeUrl(page.getURL().toString()); // We use upsert to avoid overriding existing fields in previously indexed documents String endpoint = String.format("/%s/%s/%s/_update", indexName, typeName, docId); Map<String, ?> body = ImmutableMap.of( "doc", document, "doc_as_upsert", true ); AbstractHttpEntity entity = createJsonEntity(serializeAsJson(body)); try { Response response = client.performRequest("POST", endpoint, EMPTY_MAP, entity); return response.getStatusLine().getStatusCode() == 201; } catch (IOException e) { throw new RuntimeException("Failed to index page.", e); } }
@Override public UploadPartResult uploadPart(String bucketName, String objectName, String uploadId, int partNumber, InputStream in) throws GalaxyFDSClientException { URI uri = formatUri(fdsConfig.getBaseUri(), bucketName + "/" + objectName, null); ContentType contentType = ContentType.APPLICATION_OCTET_STREAM; HashMap<String, String> params = new HashMap<String, String>(); params.put("uploadId", uploadId); params.put("partNumber", String.valueOf(partNumber)); AbstractHttpEntity requestEntity = getRequestEntity(in, contentType); HttpUriRequest httpRequest = prepareRequestMethod(uri, HttpMethod.PUT, contentType, null, params, null, requestEntity); HttpResponse response = executeHttpRequest(httpRequest, Action.UploadPart); UploadPartResult uploadPartResult = (UploadPartResult) processResponse(response, UploadPartResult.class, "upload part of object [" + objectName + "] to bucket [" + bucketName + "]" + "; part number [" + partNumber + "], upload id [" + uploadId + "]"); return uploadPartResult; }
private AbstractHttpEntity getRequestEntity(InputStream input, ContentType contentType, long inputStreamLength) throws GalaxyFDSClientException { if (input instanceof ByteArrayInputStream) { try { if (inputStreamLength > Integer.MAX_VALUE || // -1 means length unknown, use all data (inputStreamLength < 0 && inputStreamLength != -1)) { throw new GalaxyFDSClientException("Invalid length [" + inputStreamLength + "] for byteArrayInputStream"); } byte[] data = IOUtils.toByteArray(input); int len = inputStreamLength >= 0 ? (int)inputStreamLength : data.length; return new ByteArrayEntity(data, 0, len, contentType); } catch (IOException e) { throw new GalaxyFDSClientException("Failed to get content of input stream", e); } } else { BufferedInputStream bufferedInputStream = new BufferedInputStream(input); InputStreamEntity entity = new InputStreamEntity(bufferedInputStream, inputStreamLength, contentType); return entity; } }
public static AbstractHttpEntity createEntity(String paramString, Boolean paramBoolean) throws IOException { if (paramBoolean.booleanValue()) { byte[] arrayOfByte = paramString.getBytes("UTF-8"); ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(arrayOfByte.length); GZIPOutputStream localGZIPOutputStream = new GZIPOutputStream(localByteArrayOutputStream); localGZIPOutputStream.write(arrayOfByte); localGZIPOutputStream.finish(); localGZIPOutputStream.flush(); localGZIPOutputStream.close(); return new ByteArrayEntity(localByteArrayOutputStream.toByteArray()); } return new StringEntity(paramString); }
private HttpEntity getHttpEntity(final ClientRequest clientRequest) { final Object entity = clientRequest.getEntity(); if(entity == null) { return null; } return new AbstractHttpEntity() { @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { return -1; } @Override public InputStream getContent() throws IOException, IllegalStateException { return null; } @Override public void writeTo(final OutputStream outputStream) throws IOException { clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(final int contentLength) throws IOException { return outputStream; } }); clientRequest.writeEntity(); } @Override public boolean isStreaming() { return false; } }; }
@Override public HttpResponseOutputStream<StorageObject> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final S3Object object = this.getDetails(file, status); final DelayedHttpEntityCallable<StorageObject> command = new DelayedHttpEntityCallable<StorageObject>() { @Override public StorageObject call(final AbstractHttpEntity entity) throws BackgroundException { try { final RequestEntityRestStorageService client = session.getClient(); client.putObjectWithRequestEntityImpl( containerService.getContainer(file).getName(), object, entity, status.getParameters()); if(log.isDebugEnabled()) { log.debug(String.format("Saved object %s with checksum %s", file, object.getETag())); } } catch(ServiceException e) { throw new S3ExceptionMappingService().map("Upload {0} failed", e, file); } return object; } @Override public long getContentLength() { return status.getLength(); } }; return this.write(file, status, command); }
public static AbstractHttpEntity a(byte[] bArr) { if (((long) bArr.length) < a) { return new ByteArrayEntity(bArr); } OutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream); gZIPOutputStream.write(bArr); gZIPOutputStream.close(); AbstractHttpEntity byteArrayEntity = new ByteArrayEntity(byteArrayOutputStream.toByteArray()); byteArrayEntity.setContentEncoding(AsyncHttpClient.ENCODING_GZIP); new StringBuilder("gzip size:").append(bArr.length).append("->").append(byteArrayEntity.getContentLength()); return byteArrayEntity; }
private HttpEntity createEntityForEntry(GDataSerializer entry, int format) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { entry.serialize(baos, format); } catch (IOException ioe) { Log.e(TAG, "Unable to serialize entry.", ioe); throw ioe; } catch (ParseException pe) { Log.e(TAG, "Unable to serialize entry.", pe); throw new IOException("Unable to serialize entry: " + pe.getMessage()); } byte[] entryBytes = baos.toByteArray(); if (entryBytes != null && Log.isLoggable(TAG, Log.DEBUG)) { try { Log.d(TAG, "Serialized entry: " + new String(entryBytes, "UTF-8")); } catch (UnsupportedEncodingException uee) { // should not happen throw new IllegalStateException("UTF-8 should be supported!", uee); } } AbstractHttpEntity entity = new ByteArrayEntity(entryBytes); entity.setContentType(entry.getContentType()); return entity; }
void doHttpRequest(String jsonString, HttpPost httpPost) throws UnsupportedEncodingException, IOException { HttpResponse httpResponse = null; String line = ""; StringBuffer resultBuffer = new StringBuffer(); List <NameValuePair> valuePair = new ArrayList <NameValuePair>(); valuePair.add(new BasicNameValuePair("Content-Type", "application/x-www-form-urlencoded")); AbstractHttpEntity httpEntity = new UrlEncodedFormEntity(valuePair, HTTP.UTF_8); httpEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); httpEntity.setContentEncoding("UTF-8"); // httpPost.setEntity(new StringEntity(jsonString)); // httpPost.setEntity(new UrlEncodedFormEntity(valuePair, HTTP.UTF_8)); HttpClient httpClient = HttpClientBuilder.create().build(); httpResponse = httpClient.execute(httpPost); System.out.println("Request parameters from my device : " + jsonString); System.out.println("Response code from the API server : " + httpResponse.getStatusLine().getStatusCode()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); while((line = bufferedReader.readLine()) != null) { resultBuffer.append(line); } System.out.println(resultBuffer.toString()); }
@NotNull @Override public HttpUriRequest createRequest(@NotNull ObjectMapper mapper, @NotNull String url) throws IOException { final HttpPost req = new HttpPost(url); req.addHeader(HEADER_ACCEPT, MIME_LFS_JSON); final byte[] content = mapper.writeValueAsBytes(meta); final AbstractHttpEntity entity = new ByteArrayEntity(content); entity.setContentType(MIME_LFS_JSON); req.setEntity(entity); return req; }
@NotNull @Override public HttpUriRequest createRequest(@NotNull ObjectMapper mapper, @NotNull String url) throws IOException { final HttpPut req = new HttpPut(url); final AbstractHttpEntity entity = new InputStreamEntity(streamProvider.getStream(), size); entity.setContentType(MIME_BINARY); req.setEntity(entity); return req; }
@NotNull @Override public HttpUriRequest createRequest(@NotNull ObjectMapper mapper, @NotNull String url) throws JsonProcessingException { final HttpPost req = new HttpPost(url); req.addHeader(HEADER_ACCEPT, MIME_LFS_JSON); final AbstractHttpEntity entity = new ByteArrayEntity(mapper.writeValueAsBytes(meta)); entity.setContentType(MIME_LFS_JSON); req.setEntity(entity); return req; }
/** * UPloads content on a server. * * @param content * content stream. * @return uploaded item token. * @throws RedmineException * if something goes wrong. */ public String upload(InputStream content) throws RedmineException { final URI uploadURI = getURIConfigurator().getUploadURI(); final HttpPost request = new HttpPost(uploadURI); final AbstractHttpEntity entity = new InputStreamEntity(content, -1); /* Content type required by a Redmine */ entity.setContentType("application/octet-stream"); request.setEntity(entity); final String result = send(request); return parseResponse(result, "upload", RedmineJSONParser.UPLOAD_TOKEN_PARSER); }
/** * 设置POST请求参数 * * @param request * @param postParams * @throws UnsupportedEncodingException */ private static void setPostParams(HttpRequestBase request, Map<String, String> postParams) throws UnsupportedEncodingException { List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>(); for (Map.Entry<String, String> entry : postParams.entrySet()) { postData.add(new BasicNameValuePair(entry.getKey(), entry .getValue())); } AbstractHttpEntity entity = new UrlEncodedFormEntity(postData, Consts.UTF_8); ((HttpPost) request).setEntity(entity); }
@TargetApi(Build.VERSION_CODES.FROYO) private static AbstractHttpEntity getCompressedEntity(String data) throws UnsupportedEncodingException { try { return AndroidHttpClient.getCompressedEntity(data.getBytes("UTF-8"), null); } catch (Throwable e) { return new StringEntity(data); } }
private PutObjectResult uploadWithInputStream(String bucketName, String objectName, InputStream input, long contentLength, FDSObjectMetadata metadata) throws GalaxyFDSClientException { ContentType contentType = ContentType.APPLICATION_OCTET_STREAM; if (metadata != null && metadata.getContentType() != null) { contentType = ContentType.create(metadata.getContentType()); } if (fdsConfig.isMd5CalculateEnabled()) { if (metadata == null) { metadata = new FDSObjectMetadata(); } metadata.addHeader(XiaomiHeader.MD5_ATTACHED_STREAM.getName(), "1"); try { input = new FDSMd5InputStream(input); } catch (NoSuchAlgorithmException e) { throw new GalaxyFDSClientException("Cannot init md5", e); } } URI uri = formatUri(fdsConfig.getUploadBaseUri(), bucketName + "/" + (objectName == null ? "" : objectName), (SubResource[]) null); AbstractHttpEntity requestEntity = getRequestEntity(input, contentType, contentLength); HttpMethod m = objectName == null ? HttpMethod.POST : HttpMethod.PUT; HttpUriRequest httpRequest = prepareRequestMethod(uri, m, contentType, metadata, null, null, requestEntity); HttpResponse response = executeHttpRequest(httpRequest, objectName == null ? Action.PostObject : Action.PutObject); return (PutObjectResult) processResponse(response, PutObjectResult.class, m.name() + " object [" + objectName + "] to bucket [" + bucketName + "]"); }
@Override public void handle(final RequestCommand command) throws HttpException, IOException { if (command.isBadJuju()) { final WeakReference<FastStringWriter> writer = new WeakReference<FastStringWriter>(new FastStringWriter()); getFreeMarkerService().process(normalizeTemplatePath(command.getStatusCode().asURI()), createModel(), writer.get()); final AbstractHttpEntity entity = new ByteArrayEntity(writer.get().getBuffer().toString().getBytes(), APPLICATION_HTML_CONTENT_TYPE); command.getResponse().setStatusCode(HttpStatus.SC_OK); command.getResponse().setEntity(entity); } }
/** * UPloads content on a server. * * @param content * content stream. * @return uploaded item token. * @throws com.taskadapter.redmineapi.RedMineException * if something goes wrong. */ public String upload(InputStream content) throws RedMineException { final URI uploadURI = getURIConfigurator().getUploadURI(); final HttpPost request = new HttpPost(uploadURI); final AbstractHttpEntity entity = new InputStreamEntity(content, -1); /* Content type required by a Redmine */ entity.setContentType("application/octet-stream"); request.setEntity(entity); final String result = getCommunicator().sendRequest(request); return parseResponse(result, "upload", RedmineJSONParser.UPLOAD_TOKEN_PARSER); }
/** * UPloads content on a server. * * @param content * content stream. * @return uploaded item token. * @throws RedmineException * if something goes wrong. */ public String upload(InputStream content) throws RedmineException { final URI uploadURI = getURIConfigurator().getUploadURI(); final HttpPost request = new HttpPost(uploadURI); final AbstractHttpEntity entity = new InputStreamEntity(content, -1); /* Content type required by a Redmine */ entity.setContentType("application/octet-stream"); request.setEntity(entity); final String result = getCommunicator().sendRequest(request); return parseResponse(result, "upload", RedmineJSONParser.UPLOAD_TOKEN_PARSER); }
@Override protected Void doInBackground(JSONObject... params) { JSONObject jObject = params[0]; DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); // setting json object to post request. AbstractHttpEntity entity; try { entity = new ByteArrayEntity(jObject.toString() .getBytes("UTF8")); entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(entity); // this is your response: HttpResponse response = client.execute(post); HttpEntity e = response.getEntity(); InputStream inputStream = e.getContent(); BufferedReader bf = new BufferedReader(new InputStreamReader( inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = bf.readLine()) != null) { sb.append(line + "\n"); } System.out.println(sb.toString()); jObject = new JSONObject(sb.toString()); products = MpcaJObjectsReader.readJProducts(jObject); } catch (Exception e1) { // e1.printStackTrace(); success = false; } return null; }
private void addContentTypeHeaderIfMissing( HttpEntityEnclosingRequest request) { if (request.getEntity().getContentType() == null) { ((AbstractHttpEntity) request.getEntity()) .setContentType(HTTP.OCTET_STREAM_TYPE); } }
@Override public void store(BuildCacheKey key, final BuildCacheEntryWriter output) throws BuildCacheException { final URI uri = root.resolve(key.getHashCode()); HttpPut httpPut = new HttpPut(uri); httpPut.setEntity(new AbstractHttpEntity() { @Override public boolean isRepeatable() { return true; } @Override public long getContentLength() { return -1; } @Override public InputStream getContent() throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void writeTo(OutputStream outstream) throws IOException { output.writeTo(outstream); } @Override public boolean isStreaming() { return false; } }); CloseableHttpResponse response = null; try { response = httpClient.execute(httpPut); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response for PUT {}: {}", safeUri(uri), response.getStatusLine()); } // TODO: We should examine the status to make sure the PUT was successful } catch (IOException e) { // TODO: We should consider different types of exceptions as fatal/recoverable. // Right now, everything is considered recoverable. throw new BuildCacheException(String.format("storing key '%s' in %s", key, getDescription()), e); } finally { HttpClientUtils.closeQuietly(response); } }
private Optional<JsonObject> execute(String path, Function<String, HttpEntityEnclosingRequestBase> reqFactory, Object content) { String endPoint = endPointProvider.endPoint(); String url=UrlBuilder.url(endPoint).append(false, path).build(); HttpEntityEnclosingRequestBase req = reqFactory.apply(url); try(Context timerContext = requestTimer.time()) { try(MdcContext mdcContext = MdcContext.create()) { mdcContext.put("jsonrestclient_method", req.getMethod()); mdcContext.put("jsonrestclient_endpoint", endPoint); if(content != null) { AbstractHttpEntity entity = new AbstractHttpEntity() { @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { return -1; } @Override public boolean isStreaming() { return false; } @Override public InputStream getContent() throws IOException { throw new UnsupportedOperationException("use writeTo"); } @Override public void writeTo(final OutputStream outstream) throws IOException { if(content instanceof JsonObject) { ((JsonObject)content).serialize(outstream); } else { outstream.write(content.toString().getBytes(StandardCharsets.UTF_8)); } outstream.flush(); } }; entity.setContentType("application/json; charset=utf-8"); req.setEntity(entity); return httpClient.execute(req, new JsonObjectRestResponseHandler(mdcContext,req, content)); } else { return httpClient.execute(req, new JsonObjectRestResponseHandler(mdcContext,req, null)); } } catch (EsUnavailableException | IOException e) { // mark the endpoint as failed endPointProvider.failEndpoint(endPoint); throw new EsConnectionException("could not execute "+req.getMethod()+" to " + req.getURI() +" " + e.getMessage(), e); } } }
private HttpEntity getHttpEntity(final ClientRequest clientRequest, final boolean bufferingEnabled) { final Object entity = clientRequest.getEntity(); if (entity == null) { return null; } final AbstractHttpEntity httpEntity = new AbstractHttpEntity() { public boolean isRepeatable() { return false; } public long getContentLength() { return -1; } public InputStream getContent() throws IOException, IllegalStateException { if (bufferingEnabled) { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(512); writeTo(buffer); return new ByteArrayInputStream(buffer.toByteArray()); } else { return null; } } public void writeTo(final OutputStream outputStream) throws IOException { clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() { public OutputStream getOutputStream(final int contentLength) throws IOException { return outputStream; } }); clientRequest.writeEntity(); } public boolean isStreaming() { return false; } }; if (bufferingEnabled) { try { return new BufferedHttpEntity(httpEntity); } catch (final IOException e) { throw new ProcessingException(LocalizationMessages.ERROR_BUFFERING_ENTITY(), e); } } else { return httpEntity; } }
private void addContentTypeHeaderIfMissing(final HttpEntityEnclosingRequest request) { if (request.getEntity().getContentType() == null) { ((AbstractHttpEntity) request.getEntity()).setContentType( ContentType.APPLICATION_OCTET_STREAM.getMimeType()); } }
private HttpPost createHttpPostMethod( RequestObject requestObject ) { Map<String, String> httpHeaderMap = requestObject.getHttpHeaderMap(); String strUrl = requestObject.getEndpoint(); String strXml = requestObject.getXmlMessage(); byte[] compressedXml = requestObject.getCompressedXML(); RequestSenderImpl.disableExtensiveLogging(); HttpPost post = null; try { // Prepare HTTP post post = new HttpPost( strUrl ); AbstractHttpEntity entity = null; // set Request content if ( compressedXml != null ) { entity = new ByteArrayEntity( compressedXml ); } else { try { entity = new StringEntity( strXml, "text/xml; charset=UTF-8", null ); } catch ( UnsupportedEncodingException ex ) { Logger.getLogger( RequestSenderImpl.class.getName() ).log( Level.SEVERE, null, ex ); } } // setRequestHeader (if already existent -> will be overwritten!) post.setHeader( "Content-type", "text/xml; UTF-8;" ); if ( httpHeaderMap != null ) { for ( Map.Entry<String, String> entry : httpHeaderMap.entrySet() ) { // Content-Length is automatically set by HTTPClient if ( !entry.getKey().equalsIgnoreCase( "Content-Length" ) ) { post.setHeader( entry.getKey(), entry.getValue() ); } } } post.setEntity( entity ); // set for safety reason, just in case not set! // post.setHeader("Content-Length", // String.valueOf(strXml.length())); } catch ( Exception e ) { // TODO [CHAL 2014-01-03] Not really clear why we have to catch an // exception here, but without the catch we got an error by eclipse // that an exception will not been caught Logger.getLogger( RequestSenderImpl.class.getName() ).log( Level.SEVERE, null, e ); } return post; }
private AbstractHttpEntity createJsonEntity(String mapping) { return new NStringEntity(mapping, ContentType.APPLICATION_JSON); }
@Override protected HttpPost createRequest(StringBuilder theUrlBase, AbstractHttpEntity theEntity) { HttpPost retVal = new HttpPost(theUrlBase.toString()); retVal.setEntity(theEntity); return retVal; }
@Override protected HttpRequestBase createRequest(StringBuilder theUrl, AbstractHttpEntity theEntity) { HttpPut retVal = new HttpPut(theUrl.toString()); retVal.setEntity(theEntity); return retVal; }
private AbstractHttpEntity getRequestEntity(InputStream input, ContentType contentType) throws GalaxyFDSClientException { return getRequestEntity(input, contentType, -1/* unknown length*/); }
public SimpleHttpPost(AbstractHttpEntity entity) { super(); this.entity = entity; }