List of usage examples for org.apache.http.client.methods HttpRequestBase getURI
public URI getURI()
From source file:com.reachcall.pretty.http.ProxyServlet.java
private void execute(Match match, HttpRequestBase method, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { LOG.log(Level.FINE, "Requesting {0}", method.getURI()); HttpClient client = this.getClient(); HttpResponse response = client.execute(method); for (Header h : response.getHeaders("Set-Cookie")) { String line = parseCookie(h.getValue()); LOG.log(Level.FINER, method.getURI() + "{0}", new Object[] { line }); if (line != null) { LOG.log(Level.INFO, "Bonding session {0} to host {1}", new Object[] { line, match.destination.hostAndPort() }); try { resolver.bond(line, match); } catch (ExecutionException ex) { Logger.getLogger(ProxyServlet.class.getName()).log(Level.SEVERE, null, ex); this.releaseClient(client); throw new ServletException(ex); }//from w w w .j a va 2 s .com } } int rc = response.getStatusLine().getStatusCode(); if ((rc >= HttpServletResponse.SC_MULTIPLE_CHOICES) && (rc < HttpServletResponse.SC_NOT_MODIFIED)) { String location = response.getFirstHeader(HEADER_LOCATION).getValue(); if (location == null) { throw new ServletException("Recieved status code: " + rc + " but no " + HEADER_LOCATION + " header was found in the response"); } String hostname = req.getServerName(); if ((req.getServerPort() != 80) && (req.getServerPort() != 443)) { hostname += (":" + req.getServerPort()); } hostname += req.getContextPath(); String replaced = location.replace(match.destination.hostAndPort() + match.path.getDestination(), hostname); if (replaced.startsWith("http://")) { replaced = replaced.replace("http:", req.getScheme() + ":"); } resp.sendRedirect(replaced); this.releaseClient(client); return; } else if (rc == HttpServletResponse.SC_NOT_MODIFIED) { resp.setIntHeader(HEADER_CONTENT_LENTH, 0); resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); this.releaseClient(client); return; } resp.setStatus(rc); Header[] headerArrayResponse = response.getAllHeaders(); for (Header header : headerArrayResponse) { resp.setHeader(header.getName(), header.getValue()); } if (response.getEntity() != null) { resp.setContentLength((int) response.getEntity().getContentLength()); response.getEntity().writeTo(resp.getOutputStream()); } this.releaseClient(client); LOG.finer("Done."); }
From source file:com.ooyala.api.OoyalaApiClient.java
/** * Executes the request//from w w w .ja va 2 s . c o m * * @param method The class containing the type of request (HttpGet, HttpDelete, etc) * @return The response from the server as an object of class Object. Must be casted to * either a LinkedList<String> or an HashMap<String, Object> * @throws IOException * @throws HttpStatusCodeException */ @SuppressWarnings("unchecked") private JSON executeRequest(HttpRequestBase method) throws IOException, HttpStatusCodeException { try { System.out.println(String.format("%s\t%s", method.getMethod(), method.getURI().toASCIIString())); String response = httpClient.execute(method, createResponseHandler()); if (!isResponseOK()) { throw new HttpStatusCodeException(response, getResponseCode()); } if (response.isEmpty()) { return null; } return JSONSerializer.toJSON(response); } finally { } }
From source file:org.perfrepo.client.PerfRepoClient.java
private void logHttpError(String msg, HttpRequestBase req, HttpResponse resp) throws Exception { log.error(msg + "\nHTTP Status: " + resp.getStatusLine().getStatusCode() + "\nREST API url: " + req.getURI().toString() + "\nResponse:\n" + EntityUtils.toString(resp.getEntity())); }
From source file:org.opencastproject.loadtest.engage.util.TrustedHttpClient.java
/** * Perform a request, and extract the realm and nonce values * /*ww w . ja va 2s .c o m*/ * @param request The request to execute in order to obtain the realm and nonce * @return A String[] containing the {realm, nonce} */ protected String[] getRealmAndNonce(HttpRequestBase request) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response; try { response = httpClient.execute(request); } catch (IOException e) { httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } Header[] headers = response.getHeaders("WWW-Authenticate"); if (headers == null || headers.length == 0) { logger.warn("URI {} does not support digest authentication", request.getURI()); httpClient.getConnectionManager().shutdown(); return null; } Header authRequiredResponseHeader = headers[0]; String nonce = null; String realm = null; for (HeaderElement element : authRequiredResponseHeader.getElements()) { if ("nonce".equals(element.getName())) { nonce = element.getValue(); } else if ("Digest realm".equals(element.getName())) { realm = element.getValue(); } } httpClient.getConnectionManager().shutdown(); return new String[] { realm, nonce }; }
From source file:com.mondora.chargify.controller.ChargifyAdapter.java
Object parse(Class clazz, HttpResponse response, HttpRequestBase method) throws ChargifyException { if (response.getEntity() == null) { if (logger.isTraceEnabled()) logger.trace("parse: entity is null " + method.getMethod() + " " + method.getURI().toString() + "\n" + method);// w w w . ja v a2s . co m return null; } try { if (logger.isTraceEnabled()) logger.trace("parse: " + method.getMethod() + " " + method.getURI().toString() + "\n" + method); return parse(clazz, response.getEntity().getContent()); } catch (IOException e) { if (logger.isTraceEnabled()) logger.trace("parse: " + e.getMessage(), e); if (logger.isInfoEnabled()) logger.info("parse: " + e.getMessage()); return null; } }
From source file:org.talend.dataprep.command.GenericCommand.java
/** * Runs a data prep command with the following steps: * <ul>/*from w w w .j ava2 s . c om*/ * <li>Gets the HTTP command to execute (see {@link #execute(Supplier)}.</li> * <li>Gets the behavior to adopt based on returned HTTP code (see {@link #on(HttpStatus...)}).</li> * <li>If no behavior was defined for returned code, returns an error as defined in {@link #onError(Function)}</li> * <li>If a behavior was defined, invokes defined behavior.</li> * </ul> * * @return A instance of <code>T</code>. * @throws Exception If command execution fails. */ @Override protected T run() throws Exception { final HttpRequestBase request = httpCall.get(); // update request header with security token if (StringUtils.isNotBlank(authenticationToken)) { request.addHeader(AUTHORIZATION, authenticationToken); } final HttpResponse response; try { LOGGER.trace("Requesting {} {}", request.getMethod(), request.getURI()); response = client.execute(request); } catch (Exception e) { throw onError.apply(e); } commandResponseHeaders = response.getAllHeaders(); status = HttpStatus.valueOf(response.getStatusLine().getStatusCode()); // do we have a behavior for this status code (even an error) ? // if yes use it BiFunction<HttpRequestBase, HttpResponse, T> function = behavior.get(status); if (function != null) { try { return function.apply(request, response); } catch (Exception e) { throw onError.apply(e); } } // handle response's HTTP status if (status.is4xxClientError() || status.is5xxServerError()) { // Http status >= 400 so apply onError behavior return callOnError(onError).apply(request, response); } else { // Http status is not error so apply onError behavior return behavior.getOrDefault(status, missingBehavior()).apply(request, response); } }
From source file:com.gistlabs.mechanize.AbstractResource.java
protected String inspectUri(final HttpRequestBase request, final HttpResponse response) { Header contentLocation = Util.findHeader(response, "content-location"); if (contentLocation != null && contentLocation.getValue() != null) return contentLocation.getValue(); Header mechanizeLocation = Util.findHeader(response, Mechanize.MECHANIZE_LOCATION); if (mechanizeLocation != null && mechanizeLocation.getValue() != null) return mechanizeLocation.getValue(); return request.getURI().toString(); }
From source file:eionet.webq.xforms.XFormsHTTPRequestAuthHandlerImplTest.java
@Test public void noAuthIfDifferentHostAsInstance() { String resourceUrl = "http://resource.xml"; HttpRequestBase httpRequest = new HttpGet(resourceUrl); Map<Object, Object> context = createBfContextMap(); context.put("instance", REQUEST_PARAM_KNOWN_HOST_URL + "/instance.xml"); UserFile userFile = createUserFileWithAuth(); when(userFileService.getById(anyInt())).thenReturn(userFile); when(knownHostsService.getKnownHost(anyString())).thenReturn(null); requestAuthHandler.addAuthToHttpRequest(httpRequest, context); assertThat(httpRequest.getURI().toString(), equalTo(resourceUrl)); assertThat(httpRequest.getHeaders("Authorization").length, equalTo(0)); }
From source file:com.socrata.ApiBase.java
/** * Performs a generic request against Socrata API servers * @param request Apache HttpRequest object (e.g. HttpPost, HttpGet) * @return JSON array representation of the response */// w w w. j a va 2s. c om protected JsonPayload performRequest(HttpRequestBase request) { HttpResponse response; HttpEntity entity; request.addHeader("X-App-Token", this.appToken); try { response = httpClient.execute(httpHost, request, httpContext); if (response.getStatusLine().getStatusCode() != 200) { log(java.util.logging.Level.SEVERE, "Got status " + response.getStatusLine().getStatusCode() + ": " + response.getStatusLine().toString() + " while performing request on " + request.getURI(), null); return null; } return new JsonPayload(response); } catch (Exception ex) { log(Level.SEVERE, "Error caught trying to perform HTTP request", ex); return null; } }
From source file:org.apache.zeppelin.notebook.repo.zeppelinhub.rest.HttpProxyClient.java
private String sendAndGetResponse(HttpRequestBase request) throws IOException { String data = StringUtils.EMPTY; try {/*from ww w .ja va2 s.c om*/ HttpResponse response = client.execute(request, null).get(30, TimeUnit.SECONDS); int code = response.getStatusLine().getStatusCode(); if (code == 200) { try (InputStream responseContent = response.getEntity().getContent()) { data = IOUtils.toString(responseContent, "UTF-8"); } } else { LOG.error("ZeppelinHub {} {} returned with status {} ", request.getMethod(), request.getURI(), code); throw new IOException("Cannot perform " + request.getMethod() + " request to ZeppelinHub"); } } catch (InterruptedException | ExecutionException | TimeoutException | NullPointerException e) { throw new IOException(e); } return data; }