List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:ch.netcetera.eclipse.common.net.AbstractHttpClient.java
private void configureProxySettings(HttpClient client, HttpGet get) { if (getProxyService() != null && getProxyService().getProxyData() != null && getProxyService().getProxyData().length > 0) { String requestScheme = get.getURI().getScheme(); for (IProxyData proxyData : getProxyService().getProxyData()) { if (proxyData != null && proxyData.getHost() != null && proxyData.getType().equalsIgnoreCase(requestScheme)) { HttpHost proxy = new HttpHost(proxyData.getHost(), proxyData.getPort(), requestScheme); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); break; }/* w w w. j ava 2 s .c o m*/ } } }
From source file:com.xorcode.andtweet.net.ConnectionBasicAuth.java
/** * Execute a POST request against the Twitter REST API. * /*from w w w .j a v a 2 s . c om*/ * @param url * @param client * @return String * @throws ConnectionException */ private String postRequest(String url, HttpClient client, UrlEncodedFormEntity formParams) throws ConnectionException { String result = null; int statusCode = 0; HttpPost postMethod = new HttpPost(url); try { postMethod.setHeader("User-Agent", USER_AGENT); postMethod.addHeader("Authorization", "Basic " + getCredentials()); if (formParams != null) { postMethod.setEntity(formParams); } client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); HttpResponse httpResponse = client.execute(postMethod); statusCode = httpResponse.getStatusLine().getStatusCode(); result = retrieveInputStream(httpResponse.getEntity()); } catch (Exception e) { Log.e(TAG, "postRequest: " + e.toString()); throw new ConnectionException(e); } finally { postMethod.abort(); } parseStatusCode(statusCode, url); return result; }
From source file:eu.liveGov.libraries.livegovtoolkit.Utils.RestClient.java
private void executeRequest(HttpUriRequest request, String url, int soTime, int connTime) throws Exception { HttpClient client = new DefaultHttpClient(); // ----- Set timeout -------------- // HttpParams httpParameters = new BasicHttpParams(); ////from ww w . jav a 2 s . c o m // // Set the timeout in milliseconds until a connection is established. // // The default value is zero, that means the timeout is not used. // int timeoutConnection = 1000; // HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // // Set the default socket timeout (SO_TIMEOUT) // // in milliseconds which is the timeout for waiting for data. // int timeoutSocket = 1000; // HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); client.getParams().setParameter("http.socket.timeout", soTime); client.getParams().setParameter("http.connection.timeout", connTime); // ---------------------------------- try { httpResponse = client.execute(request); } catch (Exception e) { client.getConnectionManager().shutdown(); e.printStackTrace(); throw e; } }
From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java
/** * Handles the authorization grant response * //from w w w .j av a2 s. c o m * @param authorizationGrant * The Authorization grant code * @param request * The request from which to extract parameters and perform the * authentication * @return The authenticated user token, or null if authentication is * incomplete. * @throws Exception * @throws UnsupportedEncodingException */ protected Authentication handleAuthorizationGrantResponse(String authorizationGrant, HttpServletRequest request, OIDCServerConfiguration serverConfig) { final boolean debug = logger.isDebugEnabled(); // Handle Token Endpoint interaction HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter("http.socket.timeout", new Integer(httpSocketTimeout)); // // TODO: basic auth is untested (it wasn't working last I // tested) // UsernamePasswordCredentials credentials = new // UsernamePasswordCredentials(serverConfig.getClientId(), // serverConfig.getClientSecret()); // ((DefaultHttpClient) // httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY, // credentials); // HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(factory); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("grant_type", "authorization_code"); form.add("code", authorizationGrant); form.add("redirect_uri", AbstractOIDCAuthenticationFilter.buildRedirectURI(request, null)); // pass clientId and clientSecret in post of request form.add("client_id", serverConfig.getClientId()); form.add("client_secret", serverConfig.getClientSecret()); if (debug) { logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointURI()); logger.debug("form = " + form); } ; String jsonString = null; try { jsonString = restTemplate.postForObject(serverConfig.getTokenEndpointURI(), form, String.class); } catch (HttpClientErrorException httpClientErrorException) { // Handle error logger.error("Token Endpoint error response: " + httpClientErrorException.getStatusText() + " : " + httpClientErrorException.getMessage()); throw new AuthenticationServiceException("Unable to obtain Access Token."); } logger.debug("from TokenEndpoint jsonString = " + jsonString); JsonElement jsonRoot = new JsonParser().parse(jsonString); if (jsonRoot.getAsJsonObject().get("error") != null) { // Handle error String error = jsonRoot.getAsJsonObject().get("error").getAsString(); logger.error("Token Endpoint returned: " + error); throw new AuthenticationServiceException( "Unable to obtain Access Token. Token Endpoint returned: " + error); } else { // Extract the id_token to insert into the // OpenIdConnectAuthenticationToken IdToken idToken = null; JwtSigningAndValidationService jwtValidator = getValidatorForServer(serverConfig); if (jsonRoot.getAsJsonObject().get("id_token") != null) { try { idToken = IdToken.parse(jsonRoot.getAsJsonObject().get("id_token").getAsString()); } catch (AuthenticationServiceException e) { // I suspect this could happen logger.error("Problem parsing id_token: " + e); // e.printStackTrace(); throw new AuthenticationServiceException( "Problem parsing id_token return from Token endpoint: " + e); } if (jwtValidator .validateSignature(jsonRoot.getAsJsonObject().get("id_token").getAsString()) == false) { throw new AuthenticationServiceException("Signature not validated"); } if (idToken.getClaims().getIssuer() == null) { throw new AuthenticationServiceException("Issuer is null"); } if (!idToken.getClaims().getIssuer().equals(serverConfig.getIssuer())) { throw new AuthenticationServiceException("Issuers do not match"); } if (jwtValidator.isJwtExpired(idToken)) { throw new AuthenticationServiceException("Id Token is expired"); } if (jwtValidator.validateIssuedAt(idToken) == false) { throw new AuthenticationServiceException("Id Token issuedAt failed"); } } else { // An error is unlikely, but it good security to check logger.error("Token Endpoint did not return an id_token"); throw new AuthenticationServiceException("Token Endpoint did not return an id_token"); } // Clients are required to compare nonce claim in ID token to // the nonce sent in the Authorization request. The client // stores this value as a signed session cookie to detect a // replay by third parties. // // See: OpenID Connect Messages Section 2.1.1 entitled "ID Token" // // http://openid.net/specs/openid-connect-messages-1_0.html#id_token // //String nonce = idToken.getClaims().getClaimAsString("nonce"); String nonce = idToken.getClaims().getNonce(); if (StringUtils.isBlank(nonce)) { logger.error("ID token did not contain a nonce claim."); throw new AuthenticationServiceException("ID token did not contain a nonce claim."); } Cookie nonceSignatureCookie = WebUtils.getCookie(request, NONCE_SIGNATURE_COOKIE_NAME); if (nonceSignatureCookie != null) { String sigText = nonceSignatureCookie.getValue(); if (sigText != null && !sigText.isEmpty()) { if (!verify(signer, publicKey, nonce, sigText)) { logger.error("Possible replay attack detected! " + "The comparison of the nonce in the returned " + "ID Token to the signed session " + NONCE_SIGNATURE_COOKIE_NAME + " failed."); throw new AuthenticationServiceException("Possible replay attack detected! " + "The comparison of the nonce in the returned " + "ID Token to the signed session " + NONCE_SIGNATURE_COOKIE_NAME + " failed."); } } else { logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty"); throw new AuthenticationServiceException( NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty"); } } else { logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found."); throw new AuthenticationServiceException(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found."); } // pull the user_id out as a claim on the id_token String userId = idToken.getTokenClaims().getUserId(); // construct an OpenIdConnectAuthenticationToken and return // a Authentication object w/the userId and the idToken OpenIdConnectAuthenticationToken token = new OpenIdConnectAuthenticationToken(userId, idToken); Authentication authentication = this.getAuthenticationManager().authenticate(token); return authentication; } }
From source file:com.akop.bach.ImageCache.java
public Bitmap getBitmap(String imageUrl, CachePolicy cachePol) { if (imageUrl == null || imageUrl.length() < 1) return null; File file = getCacheFile(imageUrl, cachePol); // See if it's in the local cache // (but only if not being forced to refresh) if (!cachePol.bypassCache && file.canRead()) { if (App.getConfig().logToConsole()) App.logv("Cache hit: " + file.getName()); try {/*from www.j av a 2s . co m*/ if (!cachePol.expired(System.currentTimeMillis(), file.lastModified())) return BitmapFactory.decodeFile(file.getAbsolutePath()); } catch (OutOfMemoryError e) { return null; } } // Fetch the image byte[] blob; int length; try { HttpClient client = new IgnorantHttpClient(); HttpParams params = client.getParams(); params.setParameter("http.useragent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;)"); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_MS); HttpConnectionParams.setSoTimeout(params, TIMEOUT_MS); HttpResponse resp = client.execute(new HttpGet(imageUrl)); HttpEntity entity = resp.getEntity(); if (entity == null) return null; InputStream stream = entity.getContent(); if (stream == null) return null; try { if ((length = (int) entity.getContentLength()) <= 0) { // Length is negative, perhaps content length is not set ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int chunkSize = 5000; byte[] chunk = new byte[chunkSize]; for (int r = 0; r >= 0; r = stream.read(chunk, 0, chunkSize)) byteStream.write(chunk, 0, r); blob = byteStream.toByteArray(); } else { // We know the length blob = new byte[length]; // Read the stream until nothing more to read for (int r = 0; r < length; r += stream.read(blob, r, length - r)) ; } } finally { stream.close(); entity.consumeContent(); } } catch (IOException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); return null; } // if (file.canWrite()) { FileOutputStream fos = null; try { fos = new FileOutputStream(file); if (cachePol.resizeWidth > 0 || cachePol.resizeHeight > 0) { Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length); float aspectRatio = (float) bmp.getWidth() / (float) bmp.getHeight(); int newWidth = (cachePol.resizeWidth <= 0) ? (int) ((float) cachePol.resizeHeight * aspectRatio) : cachePol.resizeWidth; int newHeight = (cachePol.resizeHeight <= 0) ? (int) ((float) cachePol.resizeWidth / aspectRatio) : cachePol.resizeHeight; Bitmap resized = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true); resized.compress(Bitmap.CompressFormat.PNG, 100, fos); return resized; } else { fos.write(blob); } if (App.getConfig().logToConsole()) App.logv("Wrote to cache: " + file.getName()); } catch (IOException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } } Bitmap bmp = null; try { bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length); } catch (Exception e) { if (App.getConfig().logToConsole()) e.printStackTrace(); } return bmp; }
From source file:at.co.blogspot.javaskeleton.WebClientDevWrapper.java
public static HttpClient wrapClient(final HttpClient base, final int port) { try {//from ww w.ja v a2 s . c o m final SSLContext ctx = SSLContext.getInstance("TLS"); final X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(final X509Certificate[] xcs, final String string) throws CertificateException { } public void checkServerTrusted(final X509Certificate[] xcs, final String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; final X509HostnameVerifier verifier = new X509HostnameVerifier() { @Override public void verify(final String string, final SSLSocket ssls) throws IOException { } @Override public void verify(final String string, final X509Certificate xc) throws SSLException { } @Override public void verify(final String string, final String[] strings, final String[] strings1) throws SSLException { } @Override public boolean verify(final String string, final SSLSession ssls) { return true; } }; ctx.init(null, new TrustManager[] { tm }, null); final SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(verifier); final ClientConnectionManager ccm = base.getConnectionManager(); final SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, port)); return new DefaultHttpClient(ccm, base.getParams()); } catch (final Exception ex) { LOG.error("Error enabling https-connections", ex); return null; } }
From source file:org.madsonic.service.PodcastService.java
@SuppressWarnings({ "unchecked" }) private void doRefreshChannel(PodcastChannel channel, boolean downloadEpisodes) { InputStream in = null;/*from w w w .j a v a 2s . com*/ HttpClient client = new DefaultHttpClient(); try { channel.setStatus(PodcastStatus.DOWNLOADING); channel.setErrorMessage(null); podcastDao.updateChannel(channel); HttpConnectionParams.setConnectionTimeout(client.getParams(), 2 * 60 * 1000); // 2 minutes HttpConnectionParams.setSoTimeout(client.getParams(), 10 * 60 * 1000); // 10 minutes HttpGet method = new HttpGet(channel.getUrl()); HttpResponse response = client.execute(method); in = response.getEntity().getContent(); Document document = new SAXBuilder().build(in); Element channelElement = document.getRootElement().getChild("channel"); channel.setTitle(channelElement.getChildTextTrim("title")); channel.setDescription(channelElement.getChildTextTrim("description")); channel.setStatus(PodcastStatus.COMPLETED); channel.setErrorMessage(null); podcastDao.updateChannel(channel); refreshEpisodes(channel, channelElement.getChildren("item")); } catch (Exception x) { LOG.warn("Failed to get/parse RSS file for Podcast channel " + channel.getUrl(), x); channel.setStatus(PodcastStatus.ERROR); channel.setErrorMessage(getErrorMessage(x)); podcastDao.updateChannel(channel); } finally { IOUtils.closeQuietly(in); client.getConnectionManager().shutdown(); } if (downloadEpisodes) { for (final PodcastEpisode episode : getEpisodes(channel.getId(), false)) { if (episode.getStatus() == PodcastStatus.NEW && episode.getUrl() != null) { downloadEpisode(episode); } } } }
From source file:com.drive.student.xutils.HttpUtils.java
/** * * HttpClient??get?./* w ww.jav a 2 s .com*/ */ public HttpResponse sendHttpGet(String urlpath, boolean isGzip) { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet request = new HttpGet(urlpath); buildHttpHeaderForGet(request);// if (isGzip) { request.addHeader("accept-encoding", "gzip"); } httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, HttpUtils.DEFAULT_CONN_TIMEOUT); // httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, HttpUtils.DEFAULT_SO_TIMEOUT); // ? return httpclient.execute(request, httpContext); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.att.api.rest.RESTClient.java
/** * Sets the proxy attributes for the specified http client. * * @param httpClient client to set proxy attributes for *///from w w w. j a v a2 s . c o m private void setProxyAttributes(HttpClient httpClient) { if (this.proxyHost != null && this.proxyPort != -1) { HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } }