List of usage examples for org.apache.http.client.methods CloseableHttpResponse getStatusLine
StatusLine getStatusLine();
From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java
private static String getErrorMessage(HttpUriRequest request, CloseableHttpResponse response) { String controllerHost = null; String controllerVersion = null; if (response.containsHeader(CommonConstants.Controller.HOST_HTTP_HEADER)) { controllerHost = response.getFirstHeader(CommonConstants.Controller.HOST_HTTP_HEADER).getValue(); controllerVersion = response.getFirstHeader(CommonConstants.Controller.VERSION_HTTP_HEADER).getValue(); }//from ww w .j a v a2 s . c om StatusLine statusLine = response.getStatusLine(); String reason; try { reason = new JSONObject(EntityUtils.toString(response.getEntity())).getString("error"); } catch (Exception e) { reason = "Failed to get reason"; } String errorMessage = String.format( "Got error status code: %d (%s) with reason: \"%s\" while sending request: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase(), reason, request.getURI()); if (controllerHost != null) { errorMessage = String.format("%s to controller: %s, version: %s", errorMessage, controllerHost, controllerVersion); } return errorMessage; }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do get./*ww w.j ava 2s.co m*/ * * @param uri * the uri * @param headers * the headers * @return the string * @throws Exception * the exception */ public static String doGet(URI uri, HashMap<String, String> headers) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); String respString = null; try { /* * HttpClient provides URIBuilder utility class to simplify creation and modification of request URIs. * * URI uri = new URIBuilder() .setScheme("http") .setHost("hc.apache.org/") // .setPath("/search") // .setParameter("q", * "httpclient") // .setParameter("btnG", "Google Search") // .setParameter("aq", "f") // .setParameter("oq", "") .build(); */ HttpGet httpGet = new HttpGet(uri); for (String key : headers.keySet()) { httpGet.addHeader(key, headers.get(key)); } CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try { System.out.println(response1.getStatusLine()); HttpEntity entity = response1.getEntity(); // do something useful with the response body if (entity != null) { respString = EntityUtils.toString(entity); } // and ensure it is fully consumed EntityUtils.consume(entity); } finally { response1.close(); } } finally { httpclient.close(); } return respString; }
From source file:org.wltea.analyzer.dic.Dictionary.java
/** * ???/*from w w w . j av a 2s. c om*/ */ private static List<String> getRemoteWords(String location) { List<String> buffer = new ArrayList<String>(); RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000) .setConnectTimeout(10 * 1000).setSocketTimeout(60 * 1000).build(); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response; BufferedReader in; HttpGet get = new HttpGet(location); get.setConfig(rc); try { response = httpclient.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String charset = "UTF-8"; // ??utf-8 if (response.getEntity().getContentType().getValue().contains("charset=")) { String contentType = response.getEntity().getContentType().getValue(); charset = contentType.substring(contentType.lastIndexOf("=") + 1); } in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset)); String line; while ((line = in.readLine()) != null) { buffer.add(line); } in.close(); response.close(); return buffer; } response.close(); } catch (ClientProtocolException e) { logger.error("getRemoteWords {} error", e, location); } catch (IllegalStateException e) { logger.error("getRemoteWords {} error", e, location); } catch (IOException e) { logger.error("getRemoteWords {} error", e, location); } return buffer; }
From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java
/** * Post a login form to the server when authentication was required by the previous request * @param httpClient The httpClient to use for the requests * @param httpContext httpContext with it's own cookie store for use with the singleton HTTP_CLIENT * Not <code>null</code>// ww w .j a v a 2s . co m * @param serverURI The RTC server * @param userId The userId to authenticate as * @param password The password to authenticate with * @param timeout The timeout period for the connection (in seconds) * @param listener The listener to report errors to. May be * <code>null</code> * @throws IOException Thrown if things go wrong * @throws InvalidCredentialsException if authentication fails */ private static CloseableHttpResponse handleFormBasedChallenge(CloseableHttpClient httpClient, HttpClientContext httpContext, String serverURI, String userId, String password, int timeout, TaskListener listener) throws IOException, InvalidCredentialsException { // The server requires an authentication: Create the login form String fullURI = getFullURI(serverURI, "j_security_check"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("j_username", userId)); //$NON-NLS-1$ nvps.add(new BasicNameValuePair("j_password", password)); //$NON-NLS-1$ HttpPost formPost = getPOST(fullURI, timeout); //$NON-NLS-1$ formPost.setEntity(new UrlEncodedFormEntity(nvps, UTF_8)); // The client submits the login form LOGGER.finer("POST: " + formPost.getURI()); //$NON-NLS-1$ CloseableHttpResponse formResponse = httpClient.execute(formPost, httpContext); int statusCode = formResponse.getStatusLine().getStatusCode(); Header header = formResponse.getFirstHeader(FORM_AUTHREQUIRED_HEADER); // check to see if the authentication was successful if (statusCode / 100 == 2 && (header != null) && (AUTHFAILED_HEADER_VALUE.equals(header.getValue()))) { closeResponse(formResponse); throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI)); } return formResponse; }
From source file:org.neo4j.ogm.drivers.http.request.HttpRequest.java
public static CloseableHttpResponse execute(CloseableHttpClient httpClient, HttpRequestBase request, Credentials credentials) throws HttpRequestException { LOGGER.debug("Thread: {}, request: {}", Thread.currentThread().getId(), request); CloseableHttpResponse response; request.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); request.setHeader(new BasicHeader(HTTP.USER_AGENT, "neo4j-ogm.java/2.0")); request.setHeader(new BasicHeader("Accept", "application/json;charset=UTF-8")); HttpAuthorization.authorize(request, credentials); // use defaults: 3 retries, 2 second wait between attempts RetryOnExceptionStrategy retryStrategy = new RetryOnExceptionStrategy(); while (retryStrategy.shouldRetry()) { try {//from w w w . j ava2s.co m response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); HttpEntity responseEntity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { String responseText = statusLine.getReasonPhrase(); if (responseEntity != null) { responseText = parseError(EntityUtils.toString(responseEntity)); LOGGER.warn("Thread: {}, response: {}", Thread.currentThread().getId(), responseText); } throw new HttpResponseException(statusLine.getStatusCode(), responseText); } if (responseEntity == null) { throw new ClientProtocolException("Response contains no content"); } return response; // don't close response yet, it is not consumed! } // if we didn't get a response at all, try again catch (NoHttpResponseException nhre) { LOGGER.warn("Thread: {}, No response from server: Retrying in {} milliseconds, retries left: {}", Thread.currentThread().getId(), retryStrategy.getTimeToWait(), retryStrategy.numberOfTriesLeft); retryStrategy.errorOccurred(); } catch (RetryException re) { throw new HttpRequestException(request, re); } catch (ClientProtocolException uhe) { throw new ConnectionException(request.getURI().toString(), uhe); } catch (IOException ioe) { throw new HttpRequestException(request, ioe); } // here we catch any exception we throw above (plus any we didn't throw ourselves), // log the problem, close any connection held by the request // and then rethrow the exception to the caller. catch (Exception exception) { LOGGER.warn("Thread: {}, exception: {}", Thread.currentThread().getId(), exception.getCause().getLocalizedMessage()); request.releaseConnection(); throw exception; } } throw new RuntimeException("Fatal Exception: Should not have occurred!"); }
From source file:org.wuspba.ctams.ws.ITBandController.java
public static void delete() throws Exception { String id;//from w w w. j av a 2 s .c om CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); id = doc.getBands().get(0).getId(); EntityUtils.consume(entity); } httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).setParameter("id", id) .build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.wuspba.ctams.ws.ITHiredJudgeController.java
protected static void delete() throws Exception { List<String> ids = new ArrayList<>(); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); for (HiredJudge j : doc.getHiredJudges()) { ids.add(j.getId());/* w w w .j a v a2s .c om*/ } EntityUtils.consume(entity); } for (String id : ids) { httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", id).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } } ITJudgeController.delete(); }
From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPIsAndInterOpsDUnitTest.java
public static void doQueryOpsUsingRestApis(String restEndpoint) { String currentQueryOp = null; try {//from w ww . j a v a 2s . c o m // Query TestCase-1 :: Prepare parameterized Queries { currentQueryOp = "findAllPeopleQuery"; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(restEndpoint + findAllPeopleQuery); post.addHeader("Content-Type", "application/json"); post.addHeader("Accept", "application/json"); CloseableHttpResponse createNamedQueryResponse = httpclient.execute(post); assertEquals(createNamedQueryResponse.getStatusLine().getStatusCode(), 201); assertNotNull(createNamedQueryResponse.getEntity()); createNamedQueryResponse.close(); post = new HttpPost(restEndpoint + findPeopleByGenderQuery); post.addHeader("Content-Type", "application/json"); post.addHeader("Accept", "application/json"); createNamedQueryResponse = httpclient.execute(post); assertEquals(createNamedQueryResponse.getStatusLine().getStatusCode(), 201); assertNotNull(createNamedQueryResponse.getEntity()); createNamedQueryResponse.close(); post = new HttpPost(restEndpoint + findPeopleByLastNameQuery); post.addHeader("Content-Type", "application/json"); post.addHeader("Accept", "application/json"); createNamedQueryResponse = httpclient.execute(post); assertEquals(createNamedQueryResponse.getStatusLine().getStatusCode(), 201); assertNotNull(createNamedQueryResponse.getEntity()); createNamedQueryResponse.close(); } // Query TestCase-2 :: List all parameterized queries { currentQueryOp = "listAllQueries"; HttpGet get = new HttpGet(restEndpoint + "/queries"); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse listAllQueriesResponse = httpclient.execute(get); assertEquals(listAllQueriesResponse.getStatusLine().getStatusCode(), 200); assertNotNull(listAllQueriesResponse.getEntity()); HttpEntity entity = listAllQueriesResponse.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; StringBuffer sb = new StringBuffer(); while ((line = reader.readLine()) != null) { sb.append(line); } listAllQueriesResponse.close(); // Check whether received response contains expected query IDs. JSONObject jsonObject = new JSONObject(sb.toString()); JSONArray jsonArray = jsonObject.getJSONArray("queries"); for (int i = 0; i < jsonArray.length(); i++) { assertTrue("PREPARE_PARAMETERIZED_QUERY: function IDs are not matched", Arrays .asList(PARAM_QUERY_IDS_ARRAY).contains(jsonArray.getJSONObject(i).getString("id"))); } } // Query TestCase-3 :: Run the specified named query passing in scalar values for query parameters. { currentQueryOp = "filterByLastName"; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(restEndpoint + "/queries/filterByLastName"); post.addHeader("Content-Type", "application/json"); post.addHeader("Accept", "application/json"); StringEntity entity = new StringEntity(QUERY_ARGS); post.setEntity(entity); CloseableHttpResponse runNamedQueryResponse = httpclient.execute(post); assertEquals(200, runNamedQueryResponse.getStatusLine().getStatusCode()); assertNotNull(runNamedQueryResponse.getEntity()); } } catch (Exception e) { throw new RuntimeException("unexpected exception", e); } }
From source file:org.wuspba.ctams.ws.ITVenueController.java
protected static void delete() throws Exception { List<String> ids = new ArrayList<>(); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); for (Venue v : doc.getVenues()) { ids.add(v.getId());/*w w w . ja va 2s .c o m*/ } EntityUtils.consume(entity); } for (String id : ids) { httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", id).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } } }
From source file:org.wuspba.ctams.ws.ITBandMemberController.java
protected static void delete() throws Exception { List<String> ids = new ArrayList<>(); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); for (BandMember m : doc.getBandMembers()) { ids.add(m.getId());//from w w w .ja v a 2 s. c om } EntityUtils.consume(entity); } for (String id : ids) { httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", id).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } } ITPersonController.delete(); }