List of usage examples for org.apache.commons.httpclient HttpMethod getParams
public abstract HttpMethodParams getParams();
From source file:org.eclipse.orion.server.cf.utils.HttpUtil.java
public static void configureHttpMethod(HttpMethod method, Target target) throws JSONException { method.addRequestHeader(new Header("Accept", "application/json")); method.addRequestHeader(new Header("Content-Type", "application/json")); //set default socket timeout for connection HttpMethodParams params = method.getParams(); params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT); method.setParams(params);/*from w w w. j av a 2s .c o m*/ if (target.getCloud().getAccessToken() != null) method.addRequestHeader(new Header("Authorization", "bearer " + target.getCloud().getAccessToken().getString("access_token"))); }
From source file:org.eclipse.orion.server.cf.utils.HttpUtil.java
public static void configureHttpMethod(HttpMethod method, Cloud cloud) throws JSONException { method.addRequestHeader(new Header("Accept", "application/json")); method.addRequestHeader(new Header("Content-Type", "application/json")); //set default socket timeout for connection HttpMethodParams params = method.getParams(); params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT); method.setParams(params);//from ww w . j a v a2 s .co m if (cloud.getAccessToken() != null) method.addRequestHeader( new Header("Authorization", "bearer " + cloud.getAccessToken().getString("access_token"))); }
From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java
/** * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for * future requests.//ww w. ja va 2 s .c o m * * @return <code>true</code> if login was successful; <code>false</code> otherwise. * @throws IOException if communication with the radio failed, e.g. because the device is not reachable. */ public boolean doLogin() throws IOException { isLoggedIn = false; // reset login flag if (httpClient == null) { httpClient = new HttpClient(); } final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin; logger.trace("opening URL:" + url); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Communication with radio failed: " + method.getStatusLine()); if (method.getStatusCode() == 403) { throw new RuntimeException("Radio does not allow connection, maybe wrong pin?"); } throw new IOException("Communication with radio failed, return code: " + statusCode); } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("login response: " + responseBody); } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { logger.trace("login successful"); sessionId = result.getSessionId(); isLoggedIn = true; return true; // login successful :-) } } catch (HttpException he) { logger.debug("Fatal protocol violation: {}", he.toString()); throw he; } catch (IOException ioe) { logger.debug("Fatal transport error: {}", ioe.toString()); throw ioe; } finally { method.releaseConnection(); } return false; // login not successful }
From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java
/** * Performs a request to the radio with addition parameters. * * Typically used for changing parameters. * * @param REST//from ww w .jav a 2 s . c o m * API requestString, e.g. "SET/netRemote.sys.power" * @param params * , e.g. "value=1" * @return request result * @throws IOException if the request failed. */ public FrontierSiliconRadioApiResult doRequest(String requestString, String params) throws IOException { // 3 retries upon failure for (int i = 0; i < 2; i++) { if (!isLoggedIn && !doLogin()) { continue; // not logged in and login was not successful - try again! } final String url = "http://" + hostname + ":" + port + "/fsapi/" + requestString + "?pin=" + pin + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params); logger.trace("calling url: '" + url + "'"); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(2, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); isLoggedIn = false; method.releaseConnection(); continue; } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("got result: " + responseBody); } else { logger.debug("got empty result"); isLoggedIn = false; method.releaseConnection(); continue; } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { return result; } isLoggedIn = false; method.releaseConnection(); continue; // try again } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); isLoggedIn = false; throw he; } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); throw ioe; } finally { method.releaseConnection(); } } isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?) return null; }
From source file:org.eclipse.smarthome.io.net.http.HttpUtil.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * // w w w. jav a2 s . c om * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be send to the given <code>url</code> or * <code>null</code> if no content should be send. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); // only configure a proxy if a host is provided if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey))); } } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } Credentials credentials = extractCredentials(url); if (credentials != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.debug(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }
From source file:org.entando.entando.plugins.jpoauthclient.aps.system.httpclient.OAuthHttpClient.java
@Override public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException { final String method = request.method; final String url = request.url.toExternalForm(); final InputStream body = request.getBody(); final boolean isDelete = DELETE.equalsIgnoreCase(method); final boolean isPost = POST.equalsIgnoreCase(method); final boolean isPut = PUT.equalsIgnoreCase(method); byte[] excerpt = null; HttpMethod httpMethod; if (isPost || isPut) { EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url); if (body != null) { ExcerptInputStream e = new ExcerptInputStream(body); String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH); entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e) : new InputStreamRequestEntity(e, Long.parseLong(length))); excerpt = e.getExcerpt();// w w w .jav a 2s. c om } httpMethod = entityEnclosingMethod; } else if (isDelete) { httpMethod = new DeleteMethod(url); } else { httpMethod = new GetMethod(url); } for (Map.Entry<String, Object> p : parameters.entrySet()) { String name = p.getKey(); String value = p.getValue().toString(); if (FOLLOW_REDIRECTS.equals(name)) { httpMethod.setFollowRedirects(Boolean.parseBoolean(value)); } else if (READ_TIMEOUT.equals(name)) { httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value)); } } for (Map.Entry<String, String> header : request.headers) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } HttpClient client = this._clientPool.getHttpClient(new URL(httpMethod.getURI().toString())); client.executeMethod(httpMethod); return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset()); }
From source file:org.gradle.api.internal.artifacts.repositories.CommonsHttpClientBackedRepository.java
private void configureMethod(HttpMethod method) { method.setRequestHeader("User-Agent", "Gradle/" + GradleVersion.current().getVersion()); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() { public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) { return false; }// w w w.j a v a 2 s . c o m }); }
From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpResourceCollection.java
private void configureMethod(HttpMethod method) { method.setRequestHeader("User-Agent", "Gradle/" + GradleVersion.current().getVersion()); method.setRequestHeader("Accept-Encoding", "identity"); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() { public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) { return false; }//from w w w . j ava2 s . c o m }); }
From source file:org.jetbrains.tfsIntegration.webservice.auth.NTLM2Scheme.java
/** * Produces NTLM authorization string for the given set of * {@link Credentials}.//from w w w.ja v a2 s. c o m * * @param credentials The set of credentials to be used for athentication * @param method The method being authenticated * * @throws InvalidCredentialsException if authentication credentials * are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return an NTLM authorization string * * @since 3.0 */ public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { if (state == UNINITIATED) { throw new IllegalStateException("NTLM authentication process was not initiated"); } NTCredentials ntcredentials = null; try { ntcredentials = (NTCredentials) credentials; } catch (ClassCastException e) { throw new InvalidCredentialsException( "Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName()); } String response; if (state == INITIATED || state == FAILED) { response = getType1MessageResponse(ntcredentials, method.getParams()); state = TYPE1_MSG_GENERATED; } else { response = getType3MessageResponse(ntlmchallenge, ntcredentials, method.getParams()); state = TYPE3_MSG_GENERATED; } return "NTLM " + response; }
From source file:org.mule.transport.http.HttpClientMessageDispatcher.java
@Override protected MuleMessage doSend(MuleEvent event) throws Exception { HttpMethod httpMethod = getMethod(event); httpConnector.setupClientAuthorization(event, httpMethod, client, endpoint); httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new MuleHttpMethodRetryHandler()); boolean releaseConn = false; try {//from ww w. j ava2 s.c om httpMethod = execute(event, httpMethod); DefaultExceptionPayload ep = null; if (returnException(event, httpMethod)) { ep = new DefaultExceptionPayload(new DispatchException(event, getEndpoint(), new HttpResponseException(httpMethod.getStatusText(), httpMethod.getStatusCode()))); } else if (httpMethod.getStatusCode() >= REDIRECT_STATUS_CODE_RANGE_START) { try { return handleRedirect(httpMethod, event); } catch (Exception e) { ep = new DefaultExceptionPayload(new DispatchException(event, getEndpoint(), e)); return getResponseFromMethod(httpMethod, ep); } } releaseConn = httpMethod.getResponseBodyAsStream() == null; return getResponseFromMethod(httpMethod, ep); } catch (Exception e) { releaseConn = true; if (e instanceof DispatchException) { throw (DispatchException) e; } throw new DispatchException(event, getEndpoint(), e); } finally { if (releaseConn) { httpMethod.releaseConnection(); } } }