public void send(List<Map<Object, Object>> events, AsyncSuccessCallback<ProducedEventsResult> onSuccess, AsyncFailCallback onFail, AsyncCancelledCallback onCancel) throws IOException, InterruptedException { CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault(); httpClient.start(); String url = String.format("%s/%s/bulk-produce", this.endpoint, this.topicId); System.out.println(url); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Authorization", this.writeApiKey); httpPost.addHeader("Content-type", this.format); String jsonString = MAPPER.writeValueAsString(events); HttpEntity entity = new ByteArrayEntity(jsonString.getBytes()); httpPost.setEntity(entity); ResponseParser<ProducedEventsResult> parser = new BulkProduceEventsParser(); AsyncCallback cb = new AsyncCallback(httpClient, parser, MAPPER, onSuccess, onFail, onCancel); httpClient.execute(httpPost, cb); }
/** * Post stream * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); }
/** * Put stream * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); }
public String executeOn(String ip) throws IOException, SonosControllerException { String uri = "http://" + ip + ":" + SOAP_PORT + this.endpoint; HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "text/xml"); request.setHeader("SOAPACTION", this.service + "#" + this.action); String content = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"" + " s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><s:Body>" + "<u:" + this.action + " xmlns:u=\"" + this.service + "\">" + this.getBody() + "</u:" + this.action + ">" + "</s:Body></s:Envelope>"; HttpEntity entity = new ByteArrayEntity(content.getBytes("UTF-8")); request.setEntity(entity); HttpResponse response = getHttpClient().execute(request); String responseString = EntityUtils.toString(response.getEntity()); this.handleError(ip, responseString); return responseString; }
/** * Build the HttpEntity to be sent to the Service as part of (POST) request. Creates a off-memory * {@link FileExposingFileEntity} or a regular in-memory {@link ByteArrayEntity} depending on if the request * OutputStream fit into memory when built by calling. * * @param request - * @return - the built HttpEntity * @throws IOException - */ protected HttpEntity buildEntity(final ClientInvocation request) throws IOException { HttpEntity entityToBuild = null; DeferredFileOutputStream memoryManagedOutStream = writeRequestBodyToOutputStream(request); if (memoryManagedOutStream.isInMemory()) { ByteArrayEntity entityToBuildByteArray = new ByteArrayEntity(memoryManagedOutStream.getData()); entityToBuildByteArray.setContentType( new BasicHeader(HTTP.CONTENT_TYPE, request.getHeaders().getMediaType().toString())); entityToBuild = entityToBuildByteArray; } else { File requestBodyFile = memoryManagedOutStream.getFile(); requestBodyFile.deleteOnExit(); entityToBuild = new FileExposingFileEntity( memoryManagedOutStream.getFile(), request.getHeaders().getMediaType().toString()); } return entityToBuild; }
static Request index(IndexRequest indexRequest) { String method = Strings.hasLength(indexRequest.id()) ? HttpPut.METHOD_NAME : HttpPost.METHOD_NAME; boolean isCreate = (indexRequest.opType() == DocWriteRequest.OpType.CREATE); String endpoint = endpoint(indexRequest.index(), indexRequest.type(), indexRequest.id(), isCreate ? "_create" : null); Params parameters = Params.builder(); parameters.withRouting(indexRequest.routing()); parameters.withParent(indexRequest.parent()); parameters.withTimeout(indexRequest.timeout()); parameters.withVersion(indexRequest.version()); parameters.withVersionType(indexRequest.versionType()); parameters.withPipeline(indexRequest.getPipeline()); parameters.withRefreshPolicy(indexRequest.getRefreshPolicy()); parameters.withWaitForActiveShards(indexRequest.waitForActiveShards()); BytesRef source = indexRequest.source().toBytesRef(); ContentType contentType = ContentType.create(indexRequest.getContentType().mediaType()); HttpEntity entity = new ByteArrayEntity(source.bytes, source.offset, source.length, contentType); return new Request(method, endpoint, parameters.getParams(), entity); }
private Map put(String url, String data) throws IOException, HttpException { Map<String,Object> map = null; CredentialsProvider credentials = credentialsProvider(); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credentials) .build(); try { HttpPut httpPut = new HttpPut(url); httpPut.setHeader("Accept", "application/json"); httpPut.setHeader("Content-Type", "application/json"); HttpEntity entity = new ByteArrayEntity(data.getBytes("utf-8")); httpPut.setEntity(entity); System.out.println("Executing request " + httpPut.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPut); try { LOG.debug("----------------------------------------"); LOG.debug((String)response.getStatusLine().getReasonPhrase()); String responseBody = EntityUtils.toString(response.getEntity()); LOG.debug(responseBody); Gson gson = new Gson(); map = new HashMap<String,Object>(); map = (Map<String,Object>) gson.fromJson(responseBody, map.getClass()); LOG.debug(responseBody); } finally { response.close(); } } finally { httpclient.close(); } return map; }
/** * Put stream * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); }
/** * Handles the given exception and generates an HTTP response to be sent * back to the client to inform about the exceptional condition encountered * in the course of the request processing. * * @param ex the exception. * @param response the HTTP response. */ 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); } String message = ex.getMessage(); if (message == null) { message = ex.toString(); } byte[] msg = EncodingUtils.getAsciiBytes(message); ByteArrayEntity entity = new ByteArrayEntity(msg); entity.setContentType("text/plain; charset=US-ASCII"); response.setEntity(entity); }
HttpRequestBase makeRequest(final String method, final String path, final ByteArrayEntity data, final Header[] headers) { HttpRequestBase request; String uri = this.getAddress() + path; switch (method) { case "GET": request = new HttpGet(uri); break; case "DELETE": request = new HttpDelete(uri); break; case "PATCH": request = new HttpPatch(uri); ((HttpPatch) request).setEntity(data); break; case "POST": request = new HttpPost(uri); ((HttpPost) request).setEntity(data); break; default: throw new IllegalArgumentException(String.format("%s is not a valid HTTP method", method)); } request.setHeaders(headers); return request; }
private QueryResponse queryPath(QueryRequest request) { String path = String.format("/index/%s/query", request.getIndex().getName()); Internal.QueryRequest qr = request.toProtobuf(); ByteArrayEntity body = new ByteArrayEntity(qr.toByteArray()); try { CloseableHttpResponse response = clientExecute("POST", path, body, protobufHeaders, "Error while posting query", ReturnClientResponse.RAW_RESPONSE); HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream src = entity.getContent()) { QueryResponse queryResponse = QueryResponse.fromProtobuf(src); if (!queryResponse.isSuccess()) { throw new PilosaException(queryResponse.getErrorMessage()); } return queryResponse; } } throw new PilosaException("Server returned empty response"); } catch (IOException ex) { throw new PilosaException("Error while reading response", ex); } }
/** * HTTP POST 字节数组 * @param host * @param path * @param connectTimeout * @param headers * @param querys * @param bodys * @param signHeaderPrefixList * @param appKey * @param appSecret * @return * @throws Exception */ public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey, String appSecret) throws Exception { headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret); HttpClient httpClient = wrapClient(host); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout)); HttpPost post = new HttpPost(initUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue())); } if (bodys != null) { post.setEntity(new ByteArrayEntity(bodys)); } return convert(httpClient.execute(post)); }
/** * HTTP PUT字节数组 * @param host * @param path * @param connectTimeout * @param headers * @param querys * @param bodys * @param signHeaderPrefixList * @param appKey * @param appSecret * @return * @throws Exception */ public static Response httpPut(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey, String appSecret) throws Exception { headers = initialBasicHeader(HttpMethod.PUT, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret); HttpClient httpClient = wrapClient(host); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout)); HttpPut put = new HttpPut(initUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { put.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue())); } if (bodys != null) { put.setEntity(new ByteArrayEntity(bodys)); } return convert(httpClient.execute(put)); }
private HttpUriRequest c() { if (this.f != null) { return this.f; } if (this.j == null) { byte[] b = this.c.b(); CharSequence b2 = this.c.b(AsyncHttpClient.ENCODING_GZIP); if (b != null) { if (TextUtils.equals(b2, "true")) { this.j = b.a(b); } else { this.j = new ByteArrayEntity(b); } this.j.setContentType(this.c.c()); } } HttpEntity httpEntity = this.j; if (httpEntity != null) { HttpUriRequest httpPost = new HttpPost(b()); httpPost.setEntity(httpEntity); this.f = httpPost; } else { this.f = new HttpGet(b()); } return this.f; }
private String sendPostRequest(String url, byte[] buffer, String header) throws Throwable { // TODO: 默认值设置 CloseableHttpClient httpclient = HttpClients.createDefault(); try { URI uri = new URI(url); HttpPost httpost = new HttpPost(uri); ByteArrayEntity byteArrayEntity = new ByteArrayEntity(buffer, ContentType.create(header, "UTF-8")); httpost.setEntity(byteArrayEntity); CloseableHttpResponse response = httpclient.execute(httpost); try { int status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new Exception("Unexpected response status: " + status); } HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity, "UTF-8"); } finally { response.close(); } } finally { httpclient.close(); } }
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { MockResponse mock = mocks.get(request.getRequestLine().getMethod()); if (mock == null) throw new RuntimeException("Mock not present"); if (mock.shouldFail) throw new HttpException("Mock fail"); response.setStatusCode(mock.status); if (mock.headers != null) for (Map.Entry<String,String> e : mock.headers.entrySet()) response.setHeader(e.getKey(), e.getValue()); if (mock.body != null) response.setEntity(new ByteArrayEntity(mock.body)); else { byte[] requestBody = parseRequestBody(request); if (requestBody != null) response.setEntity(new ByteArrayEntity(requestBody)); } }
public ProducedEventResult send(Map<Object, Object> event) throws IOException, PyroclastAPIException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { String url = String.format("%s/%s/produce", this.endpoint, this.topicId); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Authorization", this.writeApiKey); httpPost.addHeader("Content-type", this.format); String jsonString = MAPPER.writeValueAsString(event); HttpEntity entity = new ByteArrayEntity(jsonString.getBytes()); httpPost.setEntity(entity); CloseableHttpResponse response; response = httpClient.execute(httpPost); ResponseParser<ProducedEventResult> parser = new ProduceEventParser(); ProducedEventResult result = parser.parseResponse(response, MAPPER); response.close(); return result; } }
public ProducedEventsResult send(List<Map<Object, Object>> events) throws IOException, PyroclastAPIException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { String url = String.format("%s/%s/bulk-produce", endpoint, this.topicId); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Authorization", this.writeApiKey); httpPost.addHeader("Content-type", this.format); String jsonString = MAPPER.writeValueAsString(events); HttpEntity entity = new ByteArrayEntity(jsonString.getBytes()); httpPost.setEntity(entity); CloseableHttpResponse response; response = httpClient.execute(httpPost); ResponseParser<ProducedEventsResult> parser = new BulkProduceEventsParser(); ProducedEventsResult tbr = parser.parseResponse(response, MAPPER); response.close(); return tbr; } }
public void send(Map<Object, Object> event, AsyncSuccessCallback<ProducedEventResult> onSuccess, AsyncFailCallback onFail, AsyncCancelledCallback onCancel) throws IOException { CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault(); httpClient.start(); String url = String.format("%s/%s/produce", this.endpoint, this.topicId); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Authorization", this.writeApiKey); httpPost.addHeader("Content-type", this.format); String jsonString = MAPPER.writeValueAsString(event); HttpEntity entity = new ByteArrayEntity(jsonString.getBytes()); httpPost.setEntity(entity); ResponseParser<ProducedEventResult> parser = new ProduceEventParser(); AsyncCallback cb = new AsyncCallback(httpClient, parser, MAPPER, onSuccess, onFail, onCancel); httpClient.execute(httpPost, cb); }
private void sendRequest(final byte[] payload) { threadPool.submit(new Runnable() { public void run() { String credentials = serverContext.getUsername() + ":" + serverContext.getPassword(); HttpPost post = new HttpPost(serverContext.getEndpoint()); post.addHeader("Content-Type", "application/json"); post.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(credentials.getBytes()))); post.setEntity(new ByteArrayEntity(payload)); try { httpClient.execute(post); } catch (IOException e) { e.printStackTrace(); } } }); }
@Test public void testCompressDecompress() throws Exception { final String s = "some kind of text"; final byte[] input = s.getBytes(Consts.ASCII); // Compress the bytes final byte[] compressed = new byte[input.length * 2]; final Deflater compresser = new Deflater(); compresser.setInput(input); compresser.finish(); final int len = compresser.deflate(compressed); final HttpEntity entity = new DeflateDecompressingEntity(new ByteArrayEntity(compressed, 0, len)); Assert.assertEquals(s, EntityUtils.toString(entity)); }
@Test public void consumesBodyOf100ContinueResponseIfItArrives() throws Exception { final HttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1); final int nbytes = 128; req.setHeader("Content-Length","" + nbytes); req.setHeader("Content-Type", "application/octet-stream"); final HttpEntity postBody = new ByteArrayEntity(HttpTestUtils.getRandomBytes(nbytes)); req.setEntity(postBody); final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req); final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_CONTINUE, "Continue"); final Flag closed = new Flag(); final ByteArrayInputStream bais = makeTrackableBody(nbytes, closed); resp.setEntity(new InputStreamEntity(bais, -1)); try { impl.ensureProtocolCompliance(wrapper, resp); } catch (final ClientProtocolException expected) { } assertTrue(closed.set || bais.read() == -1); }
protected HttpResponse sendBatchUncompressed(HttpPost httpPost, byte[] raw) throws TransportException { HttpEntity entity = new ByteArrayEntity(raw, getUncompressedContentType()); httpPost.setEntity(entity); /* * Make call */ HttpResponse resp = null; try { resp = this.client.execute(httpPost); } catch (IOException e) { throw new TransportException("failed to make call", e); } return resp; }
protected HttpResponse sendBatchCompressed(HttpPost httpPost, byte[] raw) throws TransportException { /* * Write gzip data to Entity and set content encoding to gzip */ ByteArrayEntity entity = new ByteArrayEntity(raw, ContentType.DEFAULT_BINARY); entity.setContentEncoding("gzip"); httpPost.addHeader(new BasicHeader("Accept-Encoding", "gzip")); httpPost.setEntity(entity); /* * Make call */ HttpResponse resp = null; try { resp = this.client.execute(httpPost); } catch (IOException e) { throw new TransportException("failed to make call", e); } return resp; }
private HttpClient getMockClientWithResponse(byte[] respPayload, ContentType contentType, int status) throws IOException { HttpClient mockClient = mock(HttpClient.class); HttpResponse mockResponse = mock(HttpResponse.class); StatusLine mockStatusLine = mock(StatusLine.class); doReturn("expected failure").when(mockStatusLine).getReasonPhrase(); doReturn(status).when(mockStatusLine).getStatusCode(); doReturn(mockStatusLine).when(mockResponse).getStatusLine(); HttpEntity entity = new ByteArrayEntity(respPayload, contentType); doReturn(entity).when(mockResponse).getEntity(); doReturn(mockResponse).when(mockClient).execute(any(HttpPost.class)); return mockClient; }
@Override public HttpResponseMessage execute() throws RestifyHttpException { headers.all().forEach(h -> httpRequest.addHeader(h.name(), h.value())); if (httpRequest instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest; HttpEntity requestEntity = new ByteArrayEntity(byteArrayOutputStream.toByteArray()); entityEnclosingRequest.setEntity(requestEntity); } try { HttpResponse httpResponse = httpClient.execute(httpRequest, httpContext); return responseOf(httpResponse); } catch (IOException e) { throw new RestifyHttpException("I/O error on HTTP request: [" + httpRequest.getMethod() + " " + httpRequest.getURI() + "]", e); } }
/** * Handles a request by echoing the incoming request entity. * If there is no request entity, an empty document is returned. * * @param request the request * @param response the response * @param context the context * * @throws org.apache.http.HttpException in case of a problem * @throws java.io.IOException in case of an IO problem */ @Override public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT); if (!"GET".equals(method) && !"POST".equals(method) && !"PUT".equals(method) ) { throw new MethodNotSupportedException (method + " not supported by " + getClass().getName()); } response.setStatusCode(org.apache.http.HttpStatus.SC_OK); response.addHeader("Cache-Control",getCacheContent(request)); final byte[] content = getHeaderContent(request); final ByteArrayEntity bae = new ByteArrayEntity(content); response.setHeader("Connection","keep-alive"); response.setEntity(bae); }
@Test public void invokeSayHello(){ CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8080/"+ FirstRestfulService.class.getSimpleName()+"/sayHello/1.0.1"); Map<String,String> requestEntity = new HashMap<String,String>(); requestEntity.put("arg1","Bieber"); HttpEntity httpEntity = new ByteArrayEntity(JSON.toJSONBytes(requestEntity)); httpPost.setEntity(httpEntity); try { CloseableHttpResponse response = httpclient.execute(httpPost); System.out.println(response.getStatusLine()); HttpEntity entity2 = response.getEntity(); // do something useful with the response body // and ensure it is fully consumed System.out.println(EntityUtils.toString(entity2)); response.close(); } catch (IOException e) { e.printStackTrace(); } }