/** * Sends a POST request with a file and returns the response. * * @param endpoint The endpoint to send the request to. * @param file The file to upload * @param responseClass The class to deserialise the Json response to. Can be null if no response * message is expected. * @param <T> The type to deserialise the response to. * @return A {@link Response} containing the deserialised body, if any. * @throws IOException If an error occurs. * @see MultipartEntityBuilder */ private <T> Response<T> post(Endpoint endpoint, File file, Class<T> responseClass) throws IOException { if (file == null) { return post(endpoint, responseClass); } // deal with null case // Create the request HttpPost post = new HttpPost(endpoint.url()); post.setHeaders(combineHeaders()); // Add fields as text pairs MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); // Add file as binary FileBody fileBody = new FileBody(file); multipartEntityBuilder.addPart("file", fileBody); // Set the body post.setEntity(multipartEntityBuilder.build()); // Send the request and process the response try (CloseableHttpResponse response = httpClient().execute(post)) { if (String.class.isAssignableFrom(responseClass)) { String body = getResponseString(response); return new Response(response.getStatusLine(), body); } else { T body = deserialiseResponseMessage(response, responseClass); return new Response<>(response.getStatusLine(), body); } } }
/** * Sends a GET request and returns the response. * * @param endpoint The endpoint to send the request to. * @param headers Any additional headers to send with this request. You can use {@link * org.apache.http.HttpHeaders} constants for header names. * @return A {@link Path} to the downloaded content, if any. * @throws IOException If an error occurs. * @see java.nio.file.Files#probeContentType(Path) */ public Response<Path> get(Endpoint endpoint, NameValuePair... headers) throws IOException { // Create the request HttpGet get = new HttpGet(endpoint.url()); get.setHeaders(combineHeaders(headers)); Path tempFile = null; // Send the request and process the response try (CloseableHttpResponse response = httpClient().execute(get)) { if (response.getStatusLine().getStatusCode() != HttpStatus.OK_200) { return null; } // If bad response return null // Request the content HttpEntity entity = response.getEntity(); // Download the content to a temporary file if (entity != null) { tempFile = Files.createTempFile("download", "file"); try (InputStream input = entity.getContent(); OutputStream output = Files.newOutputStream(tempFile)) { IOUtils.copy(input, output); } } return new Response<>(response.getStatusLine(), tempFile); } }
/** * Sends a POST request with a file and returns the response. * * @param endpoint The endpoint to send the request to. * @param file The file to upload * @param responseClass The class to deserialise the Json response to. Can be null if no response * message is expected. * @param fields Any name-value pairs to serialise * @param <T> The type to deserialise the response to. * @return A {@link Response} containing the deserialised body, if any. * @throws IOException If an error occurs. * @see MultipartEntityBuilder */ public <T> Response<T> post( Endpoint endpoint, File file, Class<T> responseClass, NameValuePair... fields) throws IOException { if (file == null) { return post(endpoint, responseClass, fields); } // deal with null case // Create the request HttpPost post = new HttpPost(endpoint.url()); post.setHeaders(combineHeaders()); // Add fields as text pairs MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); for (NameValuePair field : fields) { multipartEntityBuilder.addTextBody(field.getName(), field.getValue()); } // Add file as binary FileBody bin = new FileBody(file); multipartEntityBuilder.addPart("file", bin); // Set the body post.setEntity(multipartEntityBuilder.build()); // Send the request and process the response try (CloseableHttpResponse response = httpClient().execute(post)) { T body = deserialiseResponseMessage(response, responseClass); return new Response<>(response.getStatusLine(), body); } }
/** * Sends a POST request and returns the response. * * @param endpoint The endpoint to send the request to. * @param responseClass The class to deserialise the Json response to. Can be null if no response * message is expected. * @param headers Any additional headers to send with this request. You can use {@link * org.apache.http.HttpHeaders} constants for header names. * @param <T> The type to deserialise the response to. * @return A {@link Response} containing the deserialised body, if any. * @throws IOException If an error occurs. */ public <T> Response<T> delete(Endpoint endpoint, Class<T> responseClass, NameValuePair... headers) throws IOException { // Create the request HttpDelete delete = new HttpDelete(endpoint.url()); delete.setHeaders(combineHeaders(headers)); // Send the request and process the response try (CloseableHttpResponse response = httpClient().execute(delete)) { T body = deserialiseResponseMessage(response, responseClass); return new Response<>(response.getStatusLine(), body); } }
/** * Sends a GET request and returns the response. * * @param endpoint The endpoint to send the request to. * @param responseClass The class to deserialise the Json response to. Can be null if no response * message is expected. * @param headers Any additional headers to send with this request. You can use {@link * org.apache.http.HttpHeaders} constants for header names. * @param <T> The type to deserialise the response to. * @return A {@link Response} containing the deserialised body, if any. * @throws IOException If an error occurs. */ public <T> Response<T> get(Endpoint endpoint, Class<T> responseClass, NameValuePair... headers) throws IOException { // Create the request HttpGet get = new HttpGet(endpoint.url()); get.setHeaders(combineHeaders(headers)); // Send the request and process the response try (CloseableHttpResponse response = httpClient().execute(get)) { // System.out.println(response); T body = deserialiseResponseMessage(response, responseClass); return new Response<>(response.getStatusLine(), body); } }
/** * Sends a POST request and returns the response. * * <p>Specifically for the use case where we have no requestMessage * * @param endpoint The endpoint to send the request to. * @param responseClass The class to deserialise the Json response to. Can be null if no response * message is expected. * @param headers Any additional headers to send with this request. You can use {@link * org.apache.http.HttpHeaders} constants for header names. * @param <T> The type to deserialise the response to. * @return A {@link Response} containing the deserialised body, if any. * @throws IOException If an error occurs. */ public <T> Response<T> post(Endpoint endpoint, Class<T> responseClass, NameValuePair... headers) throws IOException { // Create the request HttpPost post = new HttpPost(endpoint.url()); post.setHeaders(combineHeaders(headers)); // Add the request message if there is one post.setEntity(serialiseRequestMessage(null)); // Send the request and process the response try (CloseableHttpResponse response = httpClient().execute(post)) { T body = deserialiseResponseMessage(response, responseClass); return new Response<>(response.getStatusLine(), body); } }
private String safelyExecuteRequest(String url, int expectedStatus, HttpUriRequest request) { if (hostHeader != null) { request.addHeader(HOST, hostHeader); } try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatus) { throw new VerificationException( "Expected status " + expectedStatus + " for " + url + " but was " + statusCode); } return getEntityAsStringAndCloseStream(response); } catch (Exception e) { return throwUnchecked(e, String.class); } }
public void request1(String uri, int reqNum, int reqTerm) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); if (reqNum == 0) { System.out.println( String.format("request to %s infinite times with term '%d' ms", uri, reqTerm)); } else { System.out.println( String.format("request to %s '%d' times with term '%d' ms", uri, reqNum, reqTerm)); } int i = 0, tick = 0; HttpGet httpGet = new HttpGet(uri); CloseableHttpResponse response; HttpEntity entity; while (true) { usleep(reqTerm); tick = (int) (Math.random() * 10) % 2; if (tick == 0) { continue; } System.out.println("request " + httpGet.getURI()); response = httpclient.execute(httpGet); System.out.println("--> response status = " + response.getStatusLine()); // response handler try { entity = response.getEntity(); EntityUtils.consume(entity); } catch (Exception e) { System.out.println(" --> http fail:" + e.getMessage()); } finally { // Thread.sleep(5000); //테스트에만 썼다. close 지연시키려고. response.close(); } System.out.println("----------------------------------------"); if (reqNum != 0 && reqNum < ++i) { break; } } }
/** * Deserialises the given {@link CloseableHttpResponse} to the specified type. * * @param response The response. * @return The response as a String, or null if the response does not contain an entity. * @throws IOException If an error occurs. */ private String getResponseString(CloseableHttpResponse response) throws IOException { String body = null; HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream inputStream = entity.getContent()) { body = IOUtils.toString(inputStream); } } else { EntityUtils.consume(entity); } return body; }
/** * Deserialises the given {@link CloseableHttpResponse} to the specified type. * * @param response The response. * @param responseClass The type to deserialise to. * @param <T> The type to deserialise to. * @return The deserialised response, or null if the response does not contain an entity. * @throws IOException If an error occurs. */ private <T> T deserialiseResponseMessage(CloseableHttpResponse response, Class<T> responseClass) throws IOException { T body = null; HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream inputStream = entity.getContent()) { try { body = Serialiser.deserialise(inputStream, responseClass); } catch (JsonSyntaxException e) { // This can happen if an error HTTP code is received and the // body of the response doesn't contain the expected object: body = null; } } } else { EntityUtils.consume(entity); } return body; }
private <T> T executeRequest(final HttpUriRequest request, final ResponseHandler<T> handler) throws IOException { final CloseableHttpClient client = createClientInstance(); try { final CloseableHttpResponse response = client.execute(request); // Wrap the response in a buffer to facilitate error handlers re-playing the content if the // response // size is smaller than the max allowable buffer if (response.getEntity().getContentLength() >= 0 && response.getEntity().getContentLength() < config.getMaxBufferSize()) { EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity())); } // Explicit check for the authorization status of the API key if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new HyppoAuthException(config); } try { log.debug( "{} - {} : {}", request.getMethod(), request.getURI().getPath(), response.getStatusLine().getStatusCode()); return handler.handleResponse(response); } finally { IOUtils.closeQuietly(response); } } catch (Exception e) { log.error( "{} - {} : FAILED - {}", request.getMethod(), request.getURI().getPath(), e.toString()); throw e; } finally { IOUtils.closeQuietly(client); } }