HttpPost httpPost = new HttpPost(url); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { mapper.writeValue(out, requests); httpPost.setEntity(new ByteArrayEntity(out.toByteArray())); HttpResponse response = httpClient.execute(httpPost); } catch (IOException e) {
/** * Set the given serialized remote invocation as request body. * <p>The default implementation simply sets the serialized invocation as the * HttpPost's request body. This can be overridden, for example, to write a * specific encoding and to potentially set appropriate HTTP request headers. * @param config the HTTP invoker configuration that specifies the target service * @param httpPost the HttpPost to set the request body on * @param baos the ByteArrayOutputStream that contains the serialized * RemoteInvocation object * @throws java.io.IOException if thrown by I/O methods */ protected void setRequestBody( HttpInvokerClientConfiguration config, HttpPost httpPost, ByteArrayOutputStream baos) throws IOException { ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray()); entity.setContentType(getContentType()); httpPost.setEntity(entity); }
protected HttpEntity createEntity(String ct, byte[] byteArray) { final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(byteArray); byteArrayEntity.setContentType(ct); return byteArrayEntity; }
protected void handleException(final HttpException ex, final HttpResponse response) { if (ex instanceof MethodNotSupportedException) { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); } else if (ex instanceof UnsupportedHttpVersionException) { response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED); } else if (ex instanceof ProtocolException) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); } else { response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage()); ByteArrayEntity entity = new ByteArrayEntity(msg); entity.setContentType("text/plain; charset=US-ASCII"); response.setEntity(entity); }
DefaultHttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(getApiUri(metadata)); try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) { request.setEntity(new ByteArrayEntity(byteStream.toByteArray())); try (InputStream reply = response.getEntity().getContent()) { String replyMessage = IOUtils.toString(reply); if (response.getStatusLine().getStatusCode() == 200) { JSONObject jReply = (JSONObject) new JSONParser().parse(replyMessage); JSONArray jCaptions = (JSONArray) jReply.get("captions"); LOG.warn("Status = {}", response.getStatusLine()); LOG.warn("Response = {}", replyMessage);
@Override public void process(HttpRequest request, HttpContext context) throws IOException { String logId = (String) context.getAttribute(RestClients.LOG_ID_ATTRIBUTE); if (logId == null) { logId = ClientLogger.newLogId(); context.setAttribute(RestClients.LOG_ID_ATTRIBUTE, logId); } if (request instanceof HttpEntityEnclosingRequest && ((HttpEntityEnclosingRequest) request).getEntity() != null) { HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); entity.writeTo(buffer); if (!entity.isRepeatable()) { entityRequest.setEntity(new ByteArrayEntity(buffer.toByteArray())); } ClientLogger.logRequest(logId, request.getRequestLine().getMethod(), request.getRequestLine().getUri(), "", () -> new String(buffer.toByteArray())); } else { ClientLogger.logRequest(logId, request.getRequestLine().getMethod(), request.getRequestLine().getUri(), ""); } }
byte[] data = requestBuffer_.toByteArray(); requestBuffer_.reset(); post = new HttpPost(this.url_.getFile()); post.setHeader("Content-Type", "application/x-thrift"); post.setHeader("Accept", "application/x-thrift"); post.setHeader("User-Agent", "Java/THttpClient/HC"); post.setEntity(new ByteArrayEntity(data)); HttpResponse response = this.client.execute(this.host, post); int responseCode = response.getStatusLine().getStatusCode(); is = response.getEntity().getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); consume(response.getEntity()); } catch (IOException ioe) {
@Override public void sendRequest() throws IOException { request.setEntity(new ByteArrayEntity(output.toByteArray())); this.response = httpClient.execute(request); }
final ContentType requestContentType = createContentType(bulkContentType); ByteArrayOutputStream content = new ByteArrayOutputStream(); for (DocWriteRequest<?> action : bulkRequest.requests()) { DocWriteRequest.OpType opType = action.opType(); content.write(metadataSource.bytes, metadataSource.offset, metadataSource.length); content.write(separator); request.setEntity(new ByteArrayEntity(content.toByteArray(), 0, content.size(), requestContentType)); return request;
/** * Resolve Content */ protected void resolveContent(HttpEntity entity, HttpRequestBase httpRequest) throws IOException { if (entity != null) { ByteArrayOutputStream os = new ByteArrayOutputStream(); entity.writeTo(os); os.flush(); AbstractHttpEntity httpEntity = new org.apache.http.entity.ByteArrayEntity( os.toByteArray()); os.close(); httpEntity.setContentType(entity.getContentType().toString()); ((HttpEntityEnclosingRequestBase) httpRequest) .setEntity(httpEntity); } }
ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); // reqEntity is the MultipartEntity instance reqEntity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(true); bArrEntity.setContentEncoding(reqEntity.getContentEncoding()); bArrEntity.setContentType(reqEntity.getContentType()); // Set ByteArrayEntity to HttpPost post.setEntity(bArrEntity);
private DataInputStream executeRequest(HttpPost method, ByteArrayOutputStream output) { HttpResponse response = null; try { method.setEntity(new ByteArrayEntity(output.toByteArray())); response = httpClient.execute(method); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode != HttpURLConnection.HTTP_OK) { String message = response.getStatusLine().getReasonPhrase(); VoldemortIOUtils.closeQuietly(response); throw new UnreachableStoreException("HTTP request to store " + getName() + " returned status code " + statusCode + " " + message); } return new DataInputStream(response.getEntity().getContent()); } catch(IOException e) { VoldemortIOUtils.closeQuietly(response); throw new UnreachableStoreException("Could not connect to " + storeUrl + " for " + getName(), e); } }
private ByteArrayEntity generateGZIPCompressEntity(String json) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzip = null; try { gzip = new GZIPOutputStream(baos); gzip.write(json.getBytes(DEFAULT_CHARSET)); } catch (IOException e) { throw new HttpClientException(e); } finally { if(gzip != null) { try { gzip.close(); } catch (IOException e) { throw new HttpClientException(e); } } } ByteArrayEntity byteEntity = new ByteArrayEntity(baos.toByteArray()); byteEntity.setContentType("application/json"); byteEntity.setContentEncoding("gzip"); return byteEntity; }
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); entity = new ByteArrayEntity(outputStream.toByteArray()); entity.setContentEncoding("gzip"); + entity.getContentLength() + " bytes, was " + content.length entity = new ByteArrayEntity(content); entity.setContentEncoding(StandardCharsets.UTF_8.toString()); logger.info("Length of ERP query body: " + entity.getContentLength() + " bytes.");
HttpPost buildSendXMLMethod( byte[] content, String service ) throws Exception { // Prepare HTTP put // String urlString = constructUrl( service ); if ( log.isDebug() ) { log.logDebug( BaseMessages.getString( PKG, "SlaveServer.DEBUG_ConnectingTo", urlString ) ); } HttpPost postMethod = new HttpPost( urlString ); // Request content will be retrieved directly from the input stream // HttpEntity entity = new ByteArrayEntity( content ); postMethod.setEntity( entity ); postMethod.addHeader( new BasicHeader( "Content-Type", "text/xml;charset=" + Const.XML_ENCODING ) ); return postMethod; }
public static String addJobToServlet( String urlString, String xml, String authentication ) throws Exception { HttpPost method = new HttpPost( urlString ); method.setEntity( new ByteArrayEntity( xml.getBytes( "UTF-8" ) ) ); HttpClientContext context = HttpClientUtil.createPreemptiveBasicAuthentication( host, port, user, password ); method.addHeader( new BasicHeader( "Content-Type", "text/xml;charset=UTF-8" ) ); //adding authorization token if ( authentication != null ) { method.addHeader( new BasicHeader( "Authorization", authentication ) ); } //executing method HttpClient client = HttpClientManager.getInstance().createDefaultClient(); HttpResponse httpResponse = context != null ? client.execute( method, context ) : client.execute( method ); int code = httpResponse.getStatusLine().getStatusCode(); String response = HttpClientUtil.responseToString( httpResponse ); method.releaseConnection(); if ( code >= HttpStatus.SC_BAD_REQUEST ) { System.out.println( "Error occurred during job submission." ); return null; } return response; }
/** * Signal the broker that the given high-priority task is completed, providing a result. */ public void finishPriorityTask(AnalystClusterRequest clusterRequest, Object result) { String url = BROKER_BASE_URL + String.format("/complete/priority/%s", clusterRequest.taskId); HttpPost httpPost = new HttpPost(url); try { // TODO reveal any errors etc. that occurred on the worker. // Really this should probably be done with an InputStreamEntity and a JSON writer thread. byte[] serializedResult = objectMapper.writeValueAsBytes(result); httpPost.setEntity(new ByteArrayEntity(serializedResult)); HttpResponse response = httpClient.execute(httpPost); // Signal the http client library that we're done with this response object, allowing connection reuse. EntityUtils.consumeQuietly(response.getEntity()); if (response.getStatusLine().getStatusCode() == 200) { LOG.info("Successfully marked task {} as completed.", clusterRequest.taskId); } else if (response.getStatusLine().getStatusCode() == 404) { LOG.info("Task {} was not marked as completed because it doesn't exist.", clusterRequest.taskId); } else { LOG.info("Failed to mark task {} as completed, ({}).", clusterRequest.taskId, response.getStatusLine()); } } catch (Exception e) { LOG.warn("Failed to mark task {} as completed.", clusterRequest.taskId, e); } }
public void post() throws Exception{ HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.baidu.com"); String xml = "<xml>xxxx</xml>"; HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8")); post.setEntity(entity); HttpResponse response = client.execute(post); String result = EntityUtils.toString(response.getEntity()); }
private void prepareErrorResponse(final HttpResponse response, final int errorCode, final String errorMessage, final List<String> errorDetails) { final ErrorMessage message = new ErrorMessage(errorCode, errorMessage, errorDetails); try { final ByteArrayOutputStream baos = errorParser.writeInternal(message); response.setStatusCode(errorCode); response.setEntity(new ByteArrayEntity(baos.toByteArray(), PlatformJsonMessageConverter.DEFAULT_CONTENT_TYPE)); response.setHeader(HttpHeader.CONTENT_TYPE.toString(), PlatformJsonMessageConverter.DEFAULT_CONTENT_TYPE.toString()); } catch (final JsonConverterException jce) { response.setStatusCode(errorCode); response.setEntity(new ByteArrayEntity(jce.getMessage().getBytes())); } }
public void setBody(final ByteArrayOutputStream out, final ContentType contentType) { httpResponse.setEntity(new ByteArrayEntity(out.toByteArray(), contentType)); } }