List of usage examples for org.apache.commons.httpclient HttpMethod getName
public abstract String getName();
From source file:com.intuit.tank.http.BaseRequest.java
public void sendRequest(BaseResponse response, @Nonnull HttpMethod method, String requestBody) { String uri = null;/*from w w w .ja v a 2 s . c om*/ long waitTime = 0L; try { this.response = response; uri = method.getURI().toString(); logger.debug( LogUtil.getLogMessage("About to POST request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); logRequest(uri, requestBody, method.getName(), headerInformation, httpclient, false); BaseRequestHandler.setHeaders(method, headerInformation); long startTime = System.currentTimeMillis(); timestamp = new Date(startTime); httpclient.executeMethod(method); // read response body byte[] responseBody = new byte[0]; // check for no content headers if (method.getStatusCode() != 203 && method.getStatusCode() != 202 && method.getStatusCode() != 204) { try { InputStream httpInputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int curByte = httpInputStream.read(); while (curByte >= 0) { out.write(curByte); curByte = httpInputStream.read(); } responseBody = out.toByteArray(); } catch (Exception e) { logger.warn("could not get response body: " + e); } } long endTime = System.currentTimeMillis(); BaseRequestHandler.processResponse(responseBody, startTime, endTime, response, method.getStatusText(), method.getStatusCode(), method.getResponseHeaders(), httpclient.getState()); waitTime = endTime - startTime; } catch (Exception ex) { logger.error(LogUtil.getLogMessage( "Could not do " + method.getName() + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { method.releaseConnection(); } if (waitTime != 0) { doWaitDueToLongResponse(waitTime, uri); } }
From source file:com.owncloud.android.lib.common.OwnCloudClient.java
@Override public int executeMethod(HttpMethod method) throws IOException, HttpException { try { // just to log boolean customRedirectionNeeded = false; try {//from w w w . j a va 2 s .c om method.setFollowRedirects(mFollowRedirects); } catch (Exception e) { /* if (mFollowRedirects) Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() + " method, custom redirection will be used if needed"); */ customRedirectionNeeded = mFollowRedirects; } Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath()); // logCookiesAtRequest(method.getRequestHeaders(), "before"); // logCookiesAtState("before"); int status = super.executeMethod(method); if (customRedirectionNeeded) { status = patchRedirection(status, method); } // logCookiesAtRequest(method.getRequestHeaders(), "after"); // logCookiesAtState("after"); // logSetCookiesAtResponse(method.getResponseHeaders()); return status; } catch (IOException e) { Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occured", e); throw e; } }
From source file:net.adamcin.httpsig.http.apache3.Http3SignatureAuthScheme.java
public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { if (credentials instanceof SignerCredentials) { SignerCredentials creds = (SignerCredentials) credentials; String headers = this.getParameter(Constants.HEADERS); String algorithms = this.getParameter(Constants.ALGORITHMS); Challenge challenge = new Challenge(this.getRealm(), Constants.parseTokens(headers), Challenge.parseAlgorithms(algorithms)); Signer signer = creds.getSigner(); if (signer != null) { if (this.rotate) { this.rotate = false; if (!signer.rotateKeys(challenge, this.lastAuthz)) { signer.rotateKeys(challenge); return null; }//from w ww .ja v a 2 s. com } RequestContent.Builder sigBuilder = new RequestContent.Builder(); sigBuilder.setRequestTarget(method.getName(), method.getPath() + (method.getQueryString() != null ? "?" + method.getQueryString() : "")); for (Header header : method.getRequestHeaders()) { sigBuilder.addHeader(header.getName(), header.getValue()); } if (sigBuilder.build().getDate() == null) { sigBuilder.addDateNow(); method.addRequestHeader(Constants.HEADER_DATE, sigBuilder.build().getDate()); } Authorization authorization = creds.getSigner().sign(sigBuilder.build()); this.lastAuthz = authorization; if (authorization != null) { return authorization.getHeaderValue(); } } } return null; }
From source file:com.sa.npopa.samples.hbase.rest.client.Client.java
/** * Execute a transaction method given a complete URI. * @param method the transaction method//from www . j av a 2 s . c om * @param headers HTTP header values to send * @param uri a properly urlencoded URI * @return the HTTP response code * @throws IOException */ public int executeURI(HttpMethod method, Header[] headers, String uri) throws IOException { method.setURI(new URI(uri, true)); for (Map.Entry<String, String> e : extraHeaders.entrySet()) { method.addRequestHeader(e.getKey(), e.getValue()); } if (headers != null) { for (Header header : headers) { method.addRequestHeader(header); } } long startTime = System.currentTimeMillis(); int code = httpClient.executeMethod(method); long endTime = System.currentTimeMillis(); if (LOG.isDebugEnabled()) { LOG.debug(method.getName() + " " + uri + " " + code + " " + method.getStatusText() + " in " + (endTime - startTime) + " ms"); } return code; }
From source file:com.zenkey.net.prowser.Tab.java
/************************************************************************** * Writes tracing information that traces the request/response activity. * /*from w w w. j ava2s. c o m*/ * @param traceLevel * Indicates how much trace info to produce. * @param traceStream * An output stream where trace statements will be written. * @param httpMethod * The HttpMethod object of the request. */ private static void writeTrace(int traceLevel, PrintStream traceStream, HttpMethod httpMethod) { try { if (traceLevel >= TRACE_URI) { // Show trace output of the request URI traceStream .println("-------------------------------------------------------------------------------"); traceStream.println(httpMethod.getURI() + "\n"); } if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) { // Show trace output of the HTTP request line traceStream.println(httpMethod.getName() + " " + httpMethod.getPath() + (httpMethod.getQueryString() == null ? "" : "?" + httpMethod.getQueryString()) + " " + httpMethod.getParams().getVersion().toString()); } if (traceLevel >= TRACE_HEADERS) { // Show trace output of the HTTP request headers for (Header header : httpMethod.getRequestHeaders()) { traceStream.println(header.getName() + ": " + header.getValue()); } // Show trace of request entity body if (httpMethod instanceof PostMethod) { NameValuePair[] parameters = ((PostMethod) httpMethod).getParameters(); if (parameters != null) { // StringBuffer parameterString = new StringBuffer(); // for (NameValuePair parameter : parameters) { // parameterString.append(parameter.getName() + "=" + parameter.getValue() + "&"); // } // parameterString.deleteCharAt(parameterString.length() - 1); String parameterString = new String( ((ByteArrayRequestEntity) ((PostMethod) httpMethod).getRequestEntity()) .getContent(), "UTF-8"); traceStream.println(" |"); traceStream.println(" +-- " + parameterString); } } traceStream.println(); } if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) { // Show trace output of the HTTP status line traceStream.println(httpMethod.getStatusLine().toString()); } if (traceLevel >= TRACE_HEADERS) { // Show trace output of the HTTP response headers for (Header header : httpMethod.getResponseHeaders()) { traceStream.println(header.getName() + ": " + header.getValue()); } traceStream.println(); } if (traceLevel >= TRACE_BODY) { // Show trace output of the HTTP response body traceStream.println(httpMethod.getResponseBodyAsString()); traceStream.println(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:ir.keloud.android.lib.common.KeloudClient.java
@Override public int executeMethod(HttpMethod method) throws IOException, HttpException { try { // just to log boolean customRedirectionNeeded = false; try {/*w w w. j av a2 s. c o m*/ method.setFollowRedirects(mFollowRedirects); } catch (Exception e) { /* if (mFollowRedirects) Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() + " method, custom redirection will be used if needed"); */ customRedirectionNeeded = mFollowRedirects; } // Update User Agent HttpParams params = method.getParams(); String userAgent = KeloudClientManagerFactory.getUserAgent(); params.setParameter(HttpMethodParams.USER_AGENT, userAgent); Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath()); // logCookiesAtRequest(method.getRequestHeaders(), "before"); // logCookiesAtState("before"); int status = super.executeMethod(method); if (customRedirectionNeeded) { status = patchRedirection(status, method); } // logCookiesAtRequest(method.getRequestHeaders(), "after"); // logCookiesAtState("after"); // logSetCookiesAtResponse(method.getResponseHeaders()); return status; } catch (IOException e) { Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occurred", e); throw e; } }
From source file:com.sun.socialsite.web.rest.opensocial.ConsumerContext.java
/** * Adds an element to this object's context chain. If the specified * element has a "delegate" attribute, this method will retrieve the * delegation element and recursively add it also. * * @param element the ChainElement to be added to the context chain. *///from www .ja va 2 s. c om private void appendToChain(URL source, boolean loadedDirectly, JSONObject contents) throws SocialSiteException { try { ChainElement element = null; if (contents.has("attributes")) { element = new LegacyChainElement(source, loadedDirectly, contents); } else { element = new ChainElement(source, loadedDirectly, contents); } elements.add(element); if (element.contents.has("delegate")) { JSONObject delegate = element.contents.getJSONObject("delegate"); URL url = null; if (element.source != null) { url = new URL(element.source, delegate.getString("url")); } else { url = new URL(delegate.getString("url")); } HttpClient httpClient = new HttpClient(); HttpMethod method = null; if ("GET".equalsIgnoreCase(delegate.getString("method"))) { method = new GetMethod(url.toExternalForm()); } if (delegate.has("headers")) { JSONObject headers = delegate.getJSONObject("headers"); for (Iterator<?> iterator = headers.keys(); iterator.hasNext();) { String name = iterator.next().toString(); String value = headers.get(name).toString(); method.addRequestHeader(name, value); } } if (element.source != null) { method.setRequestHeader("Referer", element.source.toString()); } int responseCode = httpClient.executeMethod(method); if (responseCode == 200) { String responseBody = method.getResponseBodyAsString(); appendToChain(url, true, new JSONObject(responseBody)); if (log.isDebugEnabled()) { String msg = String.format("%s %s returned %d: %s", method.getName(), url, responseCode, responseBody); log.debug(msg); } } else { String msg = String.format("%s %s returned %d", method.getName(), url, responseCode); throw new SocialSiteException(msg); } } } catch (SocialSiteException e) { throw e; } catch (Exception e) { throw new SocialSiteException(e); } }
From source file:com.zimbra.cs.index.elasticsearch.ElasticSearchConnector.java
public int executeMethod(HttpMethod method) throws IndexStoreException, IOException { String reqBody = ""; if (ZimbraLog.elasticsearch.isTraceEnabled() && method instanceof EntityEnclosingMethod) { EntityEnclosingMethod eem = (EntityEnclosingMethod) method; RequestEntity re = eem.getRequestEntity(); if (re instanceof StringRequestEntity) { StringRequestEntity sre = (StringRequestEntity) re; reqBody = Strings.nullToEmpty(sre.getContent()); if (reqBody.length() > 0) { reqBody = String.format("\nREQUEST BODY=%s", reqBody); }/* ww w. java 2 s . c o m*/ } } try { HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); statusCode = client.executeMethod(method); } catch (ConnectException ce) { throw new ZimbraElasticSearchDownException(ce); } catch (NoHttpResponseException nhre) { // managed to connect to the ElasticSearch service but it either crashed or timed out before // we got sent back the response. // Could be a temporary problem or a problem with this particular request. // In the longer term we need to track failures related to particular items at a higher level and discard // them after retrying a number of times. throw new ZimbraElasticSearchNoResponseException(nhre); } body = method.getResponseBodyAsString(); ZimbraLog.elasticsearch.trace("ElasticSearch request:%s %s - statusCode=%d%s\nRESPONSE BODY=%s", method.getName(), method.getURI(), statusCode, reqBody, body); return statusCode; }
From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java
private void submitHttpRequest(String address, MessageObject mo) throws Exception { HttpMethod httpMethod = null; try {/*from w w w.j a va 2s. c om*/ httpMethod = buildHttpRequest(replacer.replaceValues(address, mo), mo); // authentication if (connector.isDispatcherUseAuthentication()) { List<String> authenticationPreferences = new ArrayList<String>(); if ("Digest".equalsIgnoreCase(connector.getDispatcherAuthenticationType())) { authenticationPreferences.add(AuthPolicy.DIGEST); logger.debug("using Digest authentication"); } else { authenticationPreferences.add(AuthPolicy.BASIC); logger.debug("using Basic authentication"); } client.getParams().setAuthenticationPreemptive(true); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authenticationPreferences); Credentials credentials = new UsernamePasswordCredentials( replacer.replaceValues(connector.getDispatcherUsername(), mo), replacer.replaceValues(connector.getDispatcherPassword(), mo)); client.getState().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials); logger.debug("using authentication with credentials: " + credentials); } client.getParams().setSoTimeout( NumberUtils.toInt(replacer.replaceValues(connector.getDispatcherSocketTimeout()), 30000)); // execute the method logger.debug( "executing method: type=" + httpMethod.getName() + ", uri=" + httpMethod.getURI().toString()); int statusCode = client.executeMethod(httpMethod); logger.debug("received status code: " + statusCode); String response = null; if (connector.isDispatcherIncludeHeadersInResponse()) { HttpMessageConverter converter = new HttpMessageConverter(); response = converter.httpResponseToXml(httpMethod.getStatusLine().toString(), httpMethod.getResponseHeaders(), httpMethod.getResponseBodyAsString()); } else { response = httpMethod.getResponseBodyAsString(); } if (statusCode < HttpStatus.SC_BAD_REQUEST) { messageObjectController.setSuccess(mo, response, null); // send to reply channel if ((connector.getDispatcherReplyChannelId() != null) && !connector.getDispatcherReplyChannelId().equals("sink")) { new VMRouter().routeMessageByChannelId(connector.getDispatcherReplyChannelId(), response, true); } } else { alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_404, "Received error response from HTTP server.", null); messageObjectController.setError(mo, Constants.ERROR_404, response, null, null); } } catch (Exception e) { throw e; } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:com.cloudbees.api.BeesClient.java
/** * Executes an HTTP method./*from w ww .j a v a 2 s . co m*/ */ private HttpReply executeRequest(HttpMethod httpMethod, Map<String, String> headers) throws IOException { BeesClientConfiguration conf = getBeesClientConfiguration(); HttpClient httpClient = HttpClientHelper.createClient(conf); if (encodedAccountAuthorization != null) httpMethod.setRequestHeader("Authorization", encodedAccountAuthorization); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpMethod.setRequestHeader(entry.getKey(), entry.getValue()); } } int status = 500; String rsp = "Error"; try { status = httpClient.executeMethod(httpMethod); rsp = IOUtils.toString(httpMethod.getResponseBodyAsStream()); } catch (IOException e) { throw (IOException) new IOException("Failed to " + httpMethod.getName() + " : " + httpMethod.getURI() + " : code=" + status + " response=" + e.getMessage()).initCause(e); } finally { httpMethod.releaseConnection(); } trace(status + ": " + rsp); return new HttpReply(httpMethod, status, rsp); }