List of usage examples for org.apache.http.client.methods HttpRequestBase getRequestLine
public RequestLine getRequestLine()
From source file:nl.architolk.ldt.processors.HttpClientProcessor.java
private CloseableHttpResponse executeRequest(HttpRequestBase httpRequest, CloseableHttpClient httpclient) throws ClientProtocolException, IOException { logger.info("Executing request " + httpRequest.getRequestLine()); if (httpContext != null) { logger.info("With httpContext" + httpContext.toString()); return httpclient.execute(httpRequest, httpContext); } else {//from ww w . j a v a 2s. c om return httpclient.execute(httpRequest); } }
From source file:com.partnet.automation.http.ApacheHttpAdapter.java
private Response method(HttpRequestBase httpRequestBase, String contentType, String body) { Response.Builder responseBuilder; if (httpRequestBase instanceof HttpEntityEnclosingRequestBase) { this.setEntity((HttpEntityEnclosingRequestBase) httpRequestBase, contentType, body); }// w ww .ja va 2s . c o m try (CloseableHttpClient httpclient = HttpClients.createDefault()) { LOG.debug("Executing request " + httpRequestBase.getRequestLine()); if (httpRequestBase instanceof HttpEntityEnclosingRequestBase) { HttpEntity entity = (((HttpEntityEnclosingRequestBase) httpRequestBase).getEntity()); if (entity != null) { LOG.debug("Body being sent: " + EntityUtils.toString(entity)); } } //handle response ResponseHandler<Response.Builder> responseHandler = new ResponseHandler<Response.Builder>() { @Override public Response.Builder handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { Response.Builder rb = new Response.Builder(); if (response.getEntity() != null) { rb.setBody(EntityUtils.toString(response.getEntity())); } rb.setStatusCode(response.getStatusLine().getStatusCode()); rb.setHeaders(convertApacheToHeaderAdapter(response.getAllHeaders())); if (response.getEntity() != null) { rb.setContentType(convertApacheToHeaderAdapter(response.getEntity().getContentType())[0]); } return rb; } }; //handle cookies HttpClientContext context = HttpClientContext.create(); context.setCookieStore(cookieStore); responseBuilder = httpclient.execute(httpRequestBase, responseHandler, context); responseBuilder.setCookies(convertCookieToAdapter(context.getCookieStore().getCookies())); } catch (IOException e) { throw new IllegalStateException("IOException occurred while attempting to communicate with endpoint", e); } return responseBuilder.build(); }
From source file:com.threatconnect.sdk.conn.HttpRequestExecutor.java
@Override public String execute(String path, HttpMethod type, Object obj) throws IOException { path += (path.contains("?") ? "&" : "?"); path += "createActivityLog=" + this.conn.getConfig().isActivityLogEnabled(); logger.trace("Path: " + path); String fullPath = this.conn.getConfig().getTcApiUrl() + path.replace("/api/", "/"); logger.trace("Full: " + type + ": " + fullPath); HttpRequestBase httpBase = getBase(fullPath, type); if (obj != null) applyEntityAsJSON(httpBase, obj); logger.trace("RawPath: " + httpBase.getURI().getPath()); logger.trace("Query: " + httpBase.getURI().getRawQuery()); logger.trace("Path: " + path); String headerPath = httpBase.getURI().getRawPath() + "?" + httpBase.getURI().getRawQuery(); logger.trace("HeaderPath: " + headerPath); ConnectionUtil.applyHeaders(this.conn.getConfig(), httpBase, type.toString(), headerPath); logger.trace("Request: " + httpBase.getRequestLine()); long startMs = System.currentTimeMillis(); CloseableHttpResponse response = this.conn.getApiClient().execute(httpBase); notifyListeners(type, fullPath, (System.currentTimeMillis() - startMs)); String result = null;//from w w w. j a v a 2s . co m try { logger.trace(response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); logger.trace("Response Headers: " + Arrays.toString(response.getAllHeaders())); logger.trace("Content Encoding: " + entity.getContentEncoding()); if (entity != null) { result = EntityUtils.toString(entity, StandardCharsets.UTF_8); logger.trace("Result:" + result); EntityUtils.consume(entity); } } finally { response.close(); } return result; }
From source file:com.helger.pd.client.jdk6.PDClient.java
/** * The main execution routine. Overwrite this method to add additional * properties to the call./*from w ww . j a v a 2 s .c o m*/ * * @param aRequest * The request to be executed. Never <code>null</code>. * @return The HTTP execution response. Never <code>null</code>. * @throws IOException * On HTTP error */ @Nonnull @OverrideOnDemand protected CloseableHttpResponse executeRequest(@Nonnull final HttpRequestBase aRequest) throws IOException { aRequest.setConfig(createRequestConfig()); // Contextual attributes set the local context level will take // precedence over those set at the client level. final HttpClientContext aContext = HttpClientContext.create(); if (m_aProxy != null && m_aProxyCredentials != null) { final CredentialsProvider aCredentialsProvider = new BasicCredentialsProvider(); aCredentialsProvider.setCredentials(new AuthScope(m_aProxy), m_aProxyCredentials); aContext.setCredentialsProvider(aCredentialsProvider); } if (m_aHttpClient == null) m_aHttpClient = createClientBuilder().build(); if (s_aLogger.isDebugEnabled()) s_aLogger.debug("Executing request " + aRequest.getRequestLine()); return m_aHttpClient.execute(aRequest, aContext); }
From source file:javax.microedition.ims.core.xdm.XDMServiceImpl.java
private void printRequest(HttpRequestBase httpRequest) { Logger.log(TAG, "------------------------------ Request Begin ------------------------------"); Logger.log(TAG, httpRequest.getRequestLine().toString()); for (Header header : httpRequest.getAllHeaders()) { Logger.log(TAG, header.getName() + " = " + header.getValue()); }/*from w ww . ja v a2 s. c om*/ Logger.log(TAG, "------------------------------ Request End ------------------------------"); }
From source file:com.k42b3.neodym.Http.java
public String request(int method, String url, Map<String, String> header, String body, boolean signed) throws Exception { // check cache (only GET) String cacheKey = url;//from w w w . j a va 2 s . co m if (method == Http.GET) { Cache cache = cacheManager.get(cacheKey); if (cache != null) { logger.info("Found cache for " + cacheKey + " expires in " + DateFormat.getInstance().format(cache.getExpire())); return cache.getResponse(); } } // build request HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 6000); DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); HttpRequestBase httpRequest; if (method == Http.GET) { httpRequest = new HttpGet(url); } else if (method == Http.POST) { httpRequest = new HttpPost(url); if (body != null && !body.isEmpty()) { ((HttpPost) httpRequest).setEntity(new StringEntity(body)); } } else { throw new Exception("Invalid request method"); } // add headers if (header != null) { Set<String> keys = header.keySet(); for (String k : keys) { httpRequest.addHeader(k, header.get(k)); } } // sign request if (oauth != null && signed) { oauth.signRequest(httpRequest); } // execute request logger.info("Request: " + httpRequest.getRequestLine().toString()); HttpResponse httpResponse = httpClient.execute(httpRequest); logger.info("Response: " + httpResponse.getStatusLine().toString()); HttpEntity entity = httpResponse.getEntity(); String responseContent = EntityUtils.toString(entity); // log traffic if (trafficListener != null) { TrafficItem trafficItem = new TrafficItem(); trafficItem.setRequest(httpRequest); trafficItem.setRequestContent(body); trafficItem.setResponse(httpResponse); trafficItem.setResponseContent(responseContent); trafficListener.handleRequest(trafficItem); } // check status code int statusCode = httpResponse.getStatusLine().getStatusCode(); if (!(statusCode >= 200 && statusCode < 300)) { if (!responseContent.isEmpty()) { String message = responseContent.length() > 128 ? responseContent.substring(0, 128) + "..." : responseContent; throw new Exception(message); } else { throw new Exception("No successful status code"); } } // assign last request/response lastRequest = httpRequest; lastResponse = httpResponse; // cache response if expires header is set if (method == Http.GET) { Date expire = null; Header[] headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName().toLowerCase().equals("expires")) { try { expire = DateFormat.getInstance().parse(headers[i].getValue()); } catch (Exception e) { } } } if (expire != null && expire.compareTo(new Date()) > 0) { Cache cache = new Cache(cacheKey, responseContent, expire); cacheManager.add(cache); logger.info("Add to cache " + cacheKey + " expires in " + DateFormat.getInstance().format(expire)); } } return responseContent; }
From source file:com.k42b3.neodym.oauth.Oauth.java
@SuppressWarnings("unused") private HttpEntity httpRequest(String method, String url, Map<String, String> header, String body) throws Exception { // build request HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 6000); DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); HttpRequestBase request; if (method.equals("GET")) { request = new HttpGet(url); } else if (method.equals("POST")) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("text", new StringBody(body)); request = new HttpPost(url); ((HttpPost) request).setEntity(entity); } else {/*from ww w . jav a 2 s.c o m*/ throw new Exception("Invalid request method"); } // header Set<String> keys = header.keySet(); for (String key : keys) { request.setHeader(key, header.get(key)); } // execute HTTP Get Request logger.info("Request: " + request.getRequestLine()); HttpResponse httpResponse = httpClient.execute(request); HttpEntity entity = httpResponse.getEntity(); String responseContent = EntityUtils.toString(entity); // log traffic if (trafficListener != null) { TrafficItem trafficItem = new TrafficItem(); trafficItem.setRequest(request); trafficItem.setResponse(httpResponse); trafficItem.setResponseContent(responseContent); trafficListener.handleRequest(trafficItem); } // check status code int statusCode = httpResponse.getStatusLine().getStatusCode(); if (!(statusCode >= 200 && statusCode < 300)) { JOptionPane.showMessageDialog(null, responseContent); throw new Exception("No successful status code"); } return entity; }
From source file:org.apache.marmotta.platform.core.services.http.HttpClientServiceImpl.java
/** * Execute a request./*from ww w . j a va2s . c o m*/ * * <b>ATTENTION</b> Make sure to close the {@link InputStream} in the {@link HttpEntity}, or * just use {@link #cleanupResponse(HttpResponse)}! * * @param request * @return * @throws ClientProtocolException * @throws IOException * @see #cleanupResponse(HttpResponse) * @see EntityUtils#consume(HttpEntity) */ @Override public HttpResponse execute(HttpRequestBase request) throws ClientProtocolException, IOException { final long start = System.nanoTime(); String logMessageF = "Request '{}' failed after {}"; try { final HttpResponse resp = httpClient.execute(request); logMessageF = "Request '{}' took {}"; return resp; } finally { log.debug(logMessageF, request.getRequestLine(), formatNanoDuration(System.nanoTime() - start)); } }
From source file:org.apache.marmotta.platform.core.services.http.HttpClientServiceImpl.java
/** * Execute a request and pass the response to the provided handler. * /*from www . j a v a 2 s . c o m*/ * @param request * @param handler * @return * @throws ClientProtocolException * @throws IOException */ @Override public <T> T execute(HttpRequestBase request, ResponseHandler<? extends T> handler) throws ClientProtocolException, IOException { if (handler == null) throw new IllegalArgumentException("Response handler must not be null."); final long start = System.nanoTime(); String logMessageF = "Request '{}' failed after {}"; try { final T result = httpClient.execute(request, handler); logMessageF = "Request '{}' took {}"; return result; } finally { log.debug(logMessageF, request.getRequestLine(), formatNanoDuration(System.nanoTime() - start)); } }
From source file:nl.esciencecenter.ptk.web.WebClient.java
/** * Execute Put or Post method and handle the (optional) String response. * Returns actual HTTP Status. Method does not do any (http) response status * handling. If the Put method succeeded but the HTTP status != 200 then * this value is returned and no Exception is thrown. * //from w ww . j a v a2 s . c o m * @param putOrPostmethod * - HttpPut or HttpPost method to execute * @param responseTextHolder * - Optional StringHolder for the Response: Put and Post might * nor return any response. * @param contentTypeHolder * - Optional StringHolder for the contentType (mimeType). * * @return actual HTTP Status as returned by server. * @throws WebException * if a communication error occurred. */ protected int executeAuthenticatedPut(HttpRequestBase putOrPostmethod, StringHolder responseTextHolder, StringHolder contentTypeHolder) throws WebException { if (this.httpClient == null) { throw new NullPointerException("HTTP Client not properly initialized: httpClient==null"); } logger.debugPrintf("executePutOrPost():'%s'\n", putOrPostmethod.getRequestLine()); boolean isPut = (putOrPostmethod instanceof HttpPut); boolean isPost = (putOrPostmethod instanceof HttpPost); if ((isPut == false) && (isPost == false)) { throw new IllegalArgumentException( "Method class must be either HttpPut or HttpPost. Class=" + putOrPostmethod.getClass()); } String actualUser; try { HttpResponse response; if (config.getUseBasicAuthentication()) { actualUser = config.getUsername(); String passwdStr = new String(config.getPasswordChars()); logger.debugPrintf("Using basic authentication, user=%s\n", actualUser); Header authHeader = new BasicHeader("Authorization", "Basic " + (StringUtil.base64Encode((actualUser + ":" + passwdStr).getBytes()))); putOrPostmethod.addHeader(authHeader); } response = httpClient.execute(putOrPostmethod); int status = handleStringResponse("executePutOrPost():" + putOrPostmethod.getRequestLine(), response, responseTextHolder, contentTypeHolder); this.lastHttpStatus = status; return status; } catch (ClientProtocolException e) { if ((config.getPort() == 443) && config.isHTTP()) { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, "HTTP Protocol error: Trying to speak plain http to (SSL) port 443?\n" + e.getMessage(), e); } else if (config.isHTTPS()) { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, "HTTPS Protocol error:" + e.getMessage(), e); } else { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, "HTTP Protocol error:" + e.getMessage(), e); } } catch (javax.net.ssl.SSLPeerUnverifiedException e) { throw new WebException(WebException.Reason.HTTPS_SSLEXCEPTION, "SSL Error:Remote host not authenticated or couldn't verify host certificate.\n" + e.getMessage(), e); } catch (javax.net.ssl.SSLException e) { // Super class throw new WebException(WebException.Reason.HTTPS_SSLEXCEPTION, "SSL Error:Remote host not authenticated or couldn't verify host certificate.\n" + e.getMessage(), e); } catch (java.net.NoRouteToHostException e) { throw new WebException(WebException.Reason.NO_ROUTE_TO_HOST_EXCEPTION, "No route to host: Server could be down or unreachable.\n" + e.getMessage(), e); } catch (IOException e) { throw new WebException(WebException.Reason.IOEXCEPTION, e.getMessage(), e); } }