List of usage examples for org.apache.http.client.methods HttpRequestBase getURI
public URI getURI()
From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClient.java
private CloseableHttpResponse sendRequestAndFailIfNot20x(HttpRequestBase httpRequest) { CloseableHttpResponse response = sendRequest(httpRequest); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() < 200 || statusLine.getStatusCode() > 206) { try {/*www . ja v a 2 s . c o m*/ System.out.println("hoops error occurred"); System.out.println(inputStreamAsString(response.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } throw new RuntimeException("Response had not expected status code (between 200 and 206) -> " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase() + " " + httpRequest.getMethod() + " " + httpRequest.getURI().toString()); } return response; }
From source file:org.apache.manifoldcf.agents.output.opensearchserver.OpenSearchServerConnection.java
protected void call(HttpRequestBase method) throws ManifoldCFException { CallThread ct = new CallThread(httpClient, method); try {//from ww w.j a v a 2s . com ct.start(); try { ct.finishUp(); if (!checkResultCode(ct.getResultCode())) throw new ManifoldCFException(getResultDescription()); response = ct.getResponse(); } catch (InterruptedException e) { ct.interrupt(); throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED); } } catch (java.net.SocketTimeoutException e) { setResult(e.getClass().getSimpleName().toUpperCase(Locale.ROOT), Result.ERROR, e.getMessage()); throw new ManifoldCFException( "SocketTimeoutException while calling " + method.getURI() + ": " + e.getMessage(), e); } catch (InterruptedIOException e) { setResult(e.getClass().getSimpleName().toUpperCase(Locale.ROOT), Result.ERROR, e.getMessage()); throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED); } catch (HttpException e) { setResult(e.getClass().getSimpleName().toUpperCase(Locale.ROOT), Result.ERROR, e.getMessage()); throw new ManifoldCFException("HttpException while calling " + method.getURI() + ": " + e.getMessage(), e); } catch (IOException e) { setResult(e.getClass().getSimpleName().toUpperCase(Locale.ROOT), Result.ERROR, e.getMessage()); throw new ManifoldCFException("IOException while calling " + method.getURI() + ": " + e.getMessage(), e); } }
From source file:org.cloudifysource.restclient.RestClientExecutor.java
private <T> T executeRequest(final HttpRequestBase request, final TypeReference<Response<T>> responseTypeReference) throws RestClientException { HttpResponse httpResponse = null;//from w ww. ja v a 2s . c o m try { IOException lastException = null; int numOfTrials = DEFAULT_TRIALS_NUM; if (HttpGet.METHOD_NAME.equals(request.getMethod())) { numOfTrials = GET_TRIALS_NUM; } for (int i = 0; i < numOfTrials; i++) { try { httpResponse = httpClient.execute(request); lastException = null; break; } catch (IOException e) { if (logger.isLoggable(Level.FINER)) { logger.finer("Execute get request to " + request.getURI() + ". try number " + (i + 1) + " out of " + GET_TRIALS_NUM + ", error is " + e.getMessage()); } lastException = e; } } if (lastException != null) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Failed executing " + request.getMethod() + " request to " + request.getURI() + " : " + lastException.getMessage()); } throw MessagesUtils.createRestClientIOException(RestClientMessageKeys.EXECUTION_FAILURE.getName(), lastException, request.getURI()); } String url = request.getURI().toString(); checkForError(httpResponse, url); return getResponseObject(responseTypeReference, httpResponse, url); } finally { request.abort(); } }
From source file:org.lol.reddit.cache.CacheDownload.java
private void performDownload(final HttpClient httpClient, final HttpRequestBase httpRequest) { if (mInitiator.isJson) httpRequest.setHeader("Accept-Encoding", "gzip"); final HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, mInitiator.getCookies()); final HttpResponse response; final StatusLine status; try {//w w w . j av a 2s . co m if (mCancelled) { mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled"); return; } response = httpClient.execute(httpRequest, localContext); status = response.getStatusLine(); } catch (Throwable t) { if (t.getCause() != null && t.getCause() instanceof RedirectException && httpRequest.getURI().getHost().endsWith("reddit.com")) { mInitiator.notifyFailure(RequestFailureType.REDDIT_REDIRECT, t, null, "Unable to open a connection"); } else { mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "Unable to open a connection"); } return; } if (status.getStatusCode() != 200) { mInitiator.notifyFailure(RequestFailureType.REQUEST, null, status, String.format("HTTP error %d (%s)", status.getStatusCode(), status.getReasonPhrase())); return; } if (mCancelled) { mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled"); return; } final HttpEntity entity = response.getEntity(); if (entity == null) { mInitiator.notifyFailure(RequestFailureType.CONNECTION, null, status, "Did not receive a valid HTTP response"); return; } final InputStream is; final String mimetype; try { is = entity.getContent(); mimetype = entity.getContentType() == null ? null : entity.getContentType().getValue(); } catch (Throwable t) { t.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, status, "Could not open an input stream"); return; } final NotifyOutputStream cacheOs; final CacheManager.WritableCacheFile cacheFile; if (mInitiator.cache) { try { cacheFile = manager.openNewCacheFile(mInitiator, session, mimetype); cacheOs = cacheFile.getOutputStream(); } catch (IOException e) { e.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Could not access the local cache"); return; } } else { cacheOs = null; cacheFile = null; } final long contentLength = entity.getContentLength(); if (mInitiator.isJson) { final InputStream bis; if (mInitiator.cache) { bis = new BufferedInputStream( new CachingInputStream(is, cacheOs, new CachingInputStream.BytesReadListener() { public void onBytesRead(final long total) { mInitiator.notifyProgress(total, contentLength); } }), 8 * 1024); } else { bis = new BufferedInputStream(is, 8 * 1024); } final JsonValue value; try { value = new JsonValue(bis); synchronized (this) { mInitiator.notifyJsonParseStarted(value, RRTime.utcCurrentTimeMillis(), session, false); } value.buildInThisThread(); } catch (Throwable t) { t.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream"); return; } if (mInitiator.cache && cacheFile != null) { try { mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(), session, false, mimetype); } catch (IOException e) { if (e.getMessage().contains("ENOSPC")) { mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space"); } else { mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found"); } } } } else { if (!mInitiator.cache) { BugReportActivity.handleGlobalError(mInitiator.context, "Cache disabled for non-JSON request"); return; } try { final byte[] buf = new byte[8 * 1024]; int bytesRead; long totalBytesRead = 0; while ((bytesRead = is.read(buf)) > 0) { totalBytesRead += bytesRead; cacheOs.write(buf, 0, bytesRead); mInitiator.notifyProgress(totalBytesRead, contentLength); } cacheOs.flush(); cacheOs.close(); try { mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(), session, false, mimetype); } catch (IOException e) { if (e.getMessage().contains("ENOSPC")) { mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space"); } else { mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found"); } } } catch (IOException e) { if (e.getMessage() != null && e.getMessage().contains("ENOSPC")) { mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Out of disk space"); } else { e.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.CONNECTION, e, null, "The connection was interrupted"); } } catch (Throwable t) { t.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "The connection was interrupted"); } } }
From source file:com.squid.kraken.v4.auth.RequestHelper.java
public static <T> T processRequest(Class<T> type, HttpServletRequest request, HttpRequestBase req) throws IOException, URISyntaxException, ServerUnavailableException, ServiceException, SSORedirectException {// ww w. ja v a 2s . co m // set client information to the header String reqXFF = request.getHeader(STRING_XFF_HEADER); String postXFF; if (reqXFF != null) { // X-Forwarded-For header already exists in the request logger.info(STRING_XFF_HEADER + " : " + reqXFF); if (reqXFF.length() > 0) { // just add the remoteHost to it postXFF = reqXFF + ", " + request.getRemoteHost(); } else { postXFF = request.getRemoteHost(); } } else { postXFF = request.getRemoteHost(); } // add a new X-Forwarded-For header containing the remoteHost req.addHeader(STRING_XFF_HEADER, postXFF); // execute the login request HttpResponse executeCode; try { HttpClient client = HttpClientBuilder.create().build(); executeCode = client.execute(req); } catch (ConnectException e) { // Authentication server unavailable throw new ServerUnavailableException(e); } // process the result BufferedReader rd = new BufferedReader(new InputStreamReader(executeCode.getEntity().getContent())); StringBuffer resultBuffer = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { resultBuffer.append(line); } String result = resultBuffer.toString(); T fromJson; Gson gson = new Gson(); int statusCode = executeCode.getStatusLine().getStatusCode(); if (statusCode != 200) { if (executeCode.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { String redirectURL = executeCode.getFirstHeader("Location").getValue(); throw new SSORedirectException("SSO Redirect Exception", redirectURL); } else { logger.info("Error : " + req.getURI() + " resulted in : " + result); WebServicesException exception; try { exception = gson.fromJson(result, WebServicesException.class); } catch (Exception e) { if ((statusCode >= 500) && (statusCode < 600)) { // Authentication server unavailable throw new ServerUnavailableException(); } else { throw new ServiceException(); } } throw new ServiceException(exception); } } else { // forward to input page displaying ok message try { fromJson = gson.fromJson(result, type); } catch (Exception e) { throw new ServiceException(e); } } return fromJson; }
From source file:org.georchestra.security.HeadersManagementStrategy.java
private void handleRequestCookies(HttpServletRequest originalRequest, HttpRequestBase proxyRequest, StringBuilder headersLog) { Enumeration<String> headers = originalRequest.getHeaders(COOKIE_ID); StringBuilder cookies = new StringBuilder(); while (headers.hasMoreElements()) { String value = headers.nextElement(); for (String requestCookies : value.split(";")) { String trimmed = requestCookies.trim(); if (trimmed.length() > 0) { if (!trimmed.startsWith(HeaderNames.JSESSION_ID)) { if (cookies.length() > 0) cookies.append("; "); cookies.append(trimmed); }/*from w ww .j a va 2 s . c o m*/ } } } HttpSession session = originalRequest.getSession(); String requestPath = proxyRequest.getURI().getPath(); if (session != null && session.getAttribute(HeaderNames.JSESSION_ID) != null) { Map<String, String> jessionIds = (Map) session.getAttribute(HeaderNames.JSESSION_ID); String currentPath = null; String currentId = null; for (String path : jessionIds.keySet()) { // see https://www.owasp.org/index.php/HttpOnly // removing extra suffixes for JSESSIONID cookie ("; HttpOnly") // This is related to some issues with newer versions of tomcat // and session loss, e.g.: // https://github.com/georchestra/georchestra/pull/913 String actualPath = path.split(";")[0].trim(); // the cookie we will use is the cookie with the longest matching path if (requestPath.startsWith(actualPath)) { if (logger.isDebugEnabled()) { logger.debug("Found possible matching JSessionId: Path = " + actualPath + " id=" + jessionIds.get(path) + " for " + requestPath + " of uri " + proxyRequest.getURI()); } if (currentPath == null || currentPath.length() < actualPath.length()) { currentPath = actualPath; currentId = jessionIds.get(path); } } } if (currentPath != null) { if (cookies.length() > 0) cookies.append("; "); cookies.append(currentId); } } headersLog.append("\t" + COOKIE_ID); headersLog.append("="); headersLog.append(cookies); headersLog.append("\n"); proxyRequest.addHeader(new BasicHeader(COOKIE_ID, cookies.toString())); }
From source file:com.shenit.commons.utils.HttpUtils.java
/** * Request url result with get method// w w w . jav a 2 s . co m * * @param request * @param context * @param proxy * @param cTimeout * @param soTimeout * @return */ public static String execute(HttpRequestBase request, HttpContext context, HttpHost proxy, int cTimeout, int soTimeout) { RequestConfig config = RequestConfig.custom().setConnectTimeout(cTimeout) .setConnectionRequestTimeout(soTimeout).build(); request.setConfig(config); String result = null; CloseableHttpClient client = HttpClientBuilder.create().setProxy(proxy).build(); try { if (LOG.isDebugEnabled()) LOG.debug("[execute] request -> \n>>>>>>>>>>>>>>>>\n{}\n<<<<<<<<<<<<<<<<\n", dumpRequest(request)); HttpResponse resp = client.execute(request, context); result = EntityUtils.toString(resp.getEntity(), getContentEncoding(resp)); if (LOG.isDebugEnabled()) LOG.debug("[execute] response -> \n>>>>>>>>>>>>>>>>\n{}\n<<<<<<<<<<<<<<<<\n", result); } catch (ClientProtocolException e) { LOG.warn("[execute]Error when calling url >> " + request.getURI(), e); } catch (IOException e) { LOG.warn("[execute]IOException when calling url >> " + request.getURI(), e); } return result; }
From source file:org.duracloud.common.web.RestHttpHelper.java
private HttpResponse executeRequest(String url, Method method, HttpEntity requestEntity, Map<String, String> headers) throws IOException { if (url == null || url.length() == 0) { throw new IllegalArgumentException("URL must be a non-empty value"); }/*from w w w . j av a2 s. c o m*/ HttpRequestBase httpRequest = method.getMethod(url, requestEntity); if (headers != null && headers.size() > 0) { addHeaders(httpRequest, headers); } if (log.isDebugEnabled()) { log.debug(loggingRequestText(url, method, requestEntity, headers)); } org.apache.http.HttpResponse response; if (null != credsProvider) { HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider); if (socketTimeoutMs > -1) { BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(); cm.setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeoutMs).build()); builder.setConnectionManager(cm); } CloseableHttpClient httpClient = buildClient(builder, method); // Use preemptive basic auth URI requestUri = httpRequest.getURI(); HttpHost target = new HttpHost(requestUri.getHost(), requestUri.getPort(), requestUri.getScheme()); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); response = httpClient.execute(httpRequest, localContext); } else { CloseableHttpClient httpClient = buildClient(HttpClients.custom(), method); response = httpClient.execute(httpRequest); } HttpResponse httpResponse = new HttpResponse(response); if (log.isDebugEnabled()) { log.debug(loggingResponseText(httpResponse)); } return httpResponse; }
From source file:org.instagram4j.DefaultInstagramClient.java
private JsonParser createParser(HttpResponse response, HttpRequestBase method) throws JsonParseException, IOException { HttpEntity entity = response.getEntity(); // Always try to get response body since API will often return JSON for non-200 status codes. String responseBody = entity != null ? EntityUtils.toString(entity) : null; if (responseBody != null) responseBody = responseBody.trim(); if (responseBody == null || responseBody.length() == 0) { if (response.getStatusLine().getStatusCode() >= 300) throw createInstagramException("Instagram request failed", method.getURI().toString(), response, null, null);/*w w w .j ava 2s . com*/ throw new InstagramException("Received empty response from Instagram"); } // Since sometimes the Instagram API responds with non-JSON (e.g. "Oops, an error occurred."), sniff here. if (!responseBody.startsWith("{") && !responseBody.endsWith("}")) { if (response.getStatusLine().getStatusCode() >= 300) throw createInstagramException("Instagram request failed", method.getURI().toString(), response, null, null); throw new InstagramException("Received unexpected response from Instagram: " + (responseBody.length() > 100 ? responseBody.substring(0, 100) : responseBody)); } return JSON_FACTORY.createParser(responseBody); }