List of usage examples for org.apache.http.params HttpParams setParameter
HttpParams setParameter(String str, Object obj);
From source file:org.dasein.cloud.aws.compute.EC2Method.java
protected @Nonnull HttpClient getClient() throws InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new InternalException("No context was specified for this request"); }/*from w w w.j av a 2s .com*/ boolean ssl = url.startsWith("https"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } return new DefaultHttpClient(params); }
From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java
@Override public String getOauth2UserEmail() throws IllegalArgumentException { // get the auth code... Context ctxt = getStateContext(ctxtKey); String code = (String) ctxt.getContext("code"); {/*from w w w .ja va 2 s. c o m*/ // convert the auth code into an auth token URI nakedUri; try { nakedUri = new URI(tokenUrl); } catch (URISyntaxException e2) { e2.printStackTrace(); logger.error(e2.toString()); return getSelfUrl(); } // DON'T NEED clientId on the toke request... // addCredentials(clientId, clientSecret, nakedUri.getHost()); // setup request interceptor to do preemptive auth // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0); HttpClientFactory factory = new GaeHttpClientFactoryImpl(); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS); HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(httpParams, true); // support authenticating HttpClientParams.setAuthenticating(httpParams, true); httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1); httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // setup client HttpClient client = factory.createHttpClient(httpParams); HttpPost httppost = new HttpPost(nakedUri); logger.info(httppost.getURI().toString()); // THESE ARE POST BODY ARGS... List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("grant_type", "authorization_code")); qparams.add(new BasicNameValuePair("client_id", CLIENT_ID)); qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET)); qparams.add(new BasicNameValuePair("code", code)); qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl())); UrlEncodedFormEntity postentity; try { postentity = new UrlEncodedFormEntity(qparams, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); logger.error(e1.toString()); throw new IllegalArgumentException("Unexpected"); } httppost.setEntity(postentity); HttpResponse response = null; try { response = client.execute(httppost, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("not 200: " + statusCode); return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase() + " status code: " + statusCode; } else { HttpEntity entity = response.getEntity(); if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) { ObjectMapper mapper = new ObjectMapper(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); Map<String, Object> userData = mapper.readValue(reader, Map.class); // stuff the map in the Context... for (Map.Entry<String, Object> e : userData.entrySet()) { ctxt.putContext(e.getKey(), e.getValue()); } } else { logger.error("unexpected body"); return "Error with Oauth2 token request - missing body"; } } } catch (IOException e) { throw new IllegalArgumentException(e.toString()); } } // OK if we got here, we have a valid token. // Issue the request... String email = null; { URI nakedUri; try { nakedUri = new URI(userInfoUrl); } catch (URISyntaxException e2) { e2.printStackTrace(); logger.error(e2.toString()); return getSelfUrl(); } List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token"))); URI uri; try { uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(), nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null); } catch (URISyntaxException e1) { e1.printStackTrace(); logger.error(e1.toString()); return getSelfUrl(); } // DON'T NEED clientId on the toke request... // addCredentials(clientId, clientSecret, nakedUri.getHost()); // setup request interceptor to do preemptive auth // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0); HttpClientFactory factory = new GaeHttpClientFactoryImpl(); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS); HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(httpParams, true); // support authenticating HttpClientParams.setAuthenticating(httpParams, true); httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1); httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // setup client HttpClient client = factory.createHttpClient(httpParams); HttpGet httpget = new HttpGet(uri); logger.info(httpget.getURI().toString()); HttpResponse response = null; try { response = client.execute(httpget, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("not 200: " + statusCode); return "Error - reason: " + response.getStatusLine().getReasonPhrase() + " status code: " + statusCode; } else { HttpEntity entity = response.getEntity(); if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) { ObjectMapper mapper = new ObjectMapper(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); Map<String, Object> userData = mapper.readValue(reader, Map.class); email = (String) userData.get("email"); } else { logger.error("unexpected body"); return "Error - missing body"; } } } catch (IOException e) { throw new IllegalArgumentException(e.toString()); } } return email; }
From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java
@Override public String obtainOauth2Data(String destinationUrl) throws IllegalArgumentException { // get the auth code... Context ctxt = getStateContext(ctxtKey); String code = (String) ctxt.getContext("code"); {//from w w w. j av a2s . c o m // convert the auth code into an auth token URI nakedUri; try { nakedUri = new URI(tokenUrl); } catch (URISyntaxException e2) { e2.printStackTrace(); logger.error(e2.toString()); return getSelfUrl(); } // DON'T NEED clientId on the toke request... // addCredentials(clientId, clientSecret, nakedUri.getHost()); // setup request interceptor to do preemptive auth // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0); HttpClientFactory factory = new GaeHttpClientFactoryImpl(); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS); HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(httpParams, true); // support authenticating HttpClientParams.setAuthenticating(httpParams, true); httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1); httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // setup client HttpClient client = factory.createHttpClient(httpParams); HttpPost httppost = new HttpPost(nakedUri); logger.info(httppost.getURI().toString()); // THESE ARE POST BODY ARGS... List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("grant_type", "authorization_code")); qparams.add(new BasicNameValuePair("client_id", CLIENT_ID)); qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET)); qparams.add(new BasicNameValuePair("code", code)); qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl())); UrlEncodedFormEntity postentity; try { postentity = new UrlEncodedFormEntity(qparams, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); logger.error(e1.toString()); throw new IllegalArgumentException("Unexpected"); } httppost.setEntity(postentity); HttpResponse response = null; try { response = client.execute(httppost, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("not 200: " + statusCode); return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase() + " status code: " + statusCode; } else { HttpEntity entity = response.getEntity(); if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) { ObjectMapper mapper = new ObjectMapper(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); Map<String, Object> userData = mapper.readValue(reader, Map.class); // stuff the map in the Context... for (Map.Entry<String, Object> e : userData.entrySet()) { ctxt.putContext(e.getKey(), e.getValue()); } } else { logger.error("unexpected body"); return "Error with Oauth2 token request - unexpected body"; } } } catch (IOException e) { throw new IllegalArgumentException(e.toString()); } } // OK if we got here, we have a valid token. // Issue the request... { URI nakedUri; try { nakedUri = new URI(destinationUrl); } catch (URISyntaxException e2) { e2.printStackTrace(); logger.error(e2.toString()); return getSelfUrl(); } List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token"))); URI uri; try { uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(), nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null); } catch (URISyntaxException e1) { e1.printStackTrace(); logger.error(e1.toString()); return getSelfUrl(); } // DON'T NEED clientId on the toke request... // addCredentials(clientId, clientSecret, nakedUri.getHost()); // setup request interceptor to do preemptive auth // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0); HttpClientFactory factory = new GaeHttpClientFactoryImpl(); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS); HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(httpParams, true); // support authenticating HttpClientParams.setAuthenticating(httpParams, true); httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1); httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // setup client HttpClient client = factory.createHttpClient(httpParams); HttpGet httpget = new HttpGet(uri); logger.info(httpget.getURI().toString()); HttpResponse response = null; try { response = client.execute(httpget, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("not 200: " + statusCode); return "Error"; } else { HttpEntity entity = response.getEntity(); if (entity != null) { String contentType = entity.getContentType().getValue(); if (contentType.toLowerCase().contains("xml")) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuilder b = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { b.append(line); } String value = b.toString(); return value; } else { logger.error("unexpected body"); return "Error"; } } else { logger.error("unexpected missing body"); return "Error"; } } } catch (IOException e) { throw new IllegalArgumentException(e.toString()); } } }
From source file:com.android.exchange.SyncManager.java
static public synchronized ClientConnectionManager getClientConnectionManager() { if (sClientConnectionManager == null) { // After two tries, kill the process. Most likely, this will happen in the background // The service will restart itself after about 5 seconds if (sClientConnectionManagerShutdownCount > MAX_CLIENT_CONNECTION_MANAGER_SHUTDOWNS) { alwaysLog("Shutting down process to unblock threads"); Process.killProcess(Process.myPid()); }//from w w w.ja v a 2 s .co m // Create a registry for our three schemes; http and https will use built-in factories SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // Use "insecure" socket factory. SSLSocketFactory sf = new SSLSocketFactory(SSLUtils.getSSLSocketFactory(true)); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Register the httpts scheme with our factory registry.register(new Scheme("httpts", sf, 443)); // And create a ccm with our registry HttpParams params = new BasicHttpParams(); params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, sConnPerRoute); sClientConnectionManager = new ThreadSafeClientConnManager(params, registry); } // Null is a valid return result if we get an exception return sClientConnectionManager; }
From source file:com.mwebster.exchange.SyncManager.java
static public synchronized ClientConnectionManager getClientConnectionManager(String accountUUID) { Log.d(TAG, "Requesting SSL factory for account UUID: " + accountUUID); if (accountUUID == null && validationKeyStore != null) { // Validating account, use temporarily provided keystore Log.d(TAG, "Create SSL factory with validation keystore"); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); try {//w w w . j av a 2 s. c om registry.register(new Scheme("https", new SSLSocketFactory(validationKeyStore, ""), 443)); } catch (Exception e) { throw new Error(e); } // Use "insecure" socket factory. SSLSocketFactory sf = new SSLSocketFactory(SSLUtils.getSSLSocketFactory(true)); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Register the httpts scheme with our factory registry.register(new Scheme("httpts", sf, 443)); HttpParams params = new BasicHttpParams(); params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 3); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, 3); return new SingleClientConnManager(params, registry); } ClientConnectionManager clientConnectionManager = clientConnectionManagerMap.get(accountUUID); if (clientConnectionManager == null) { try { // Create a registry for our three schemes; http and https will // use built-in factories // And create a ccm with our registry SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); if (accountUUID != null && INSTANCE.getFileStreamPath(accountUUID).exists()) { Log.d(TAG, "Create SSL factory with keystore"); KeyStore.PasswordProtection protection = new KeyStore.PasswordProtection( getPassword(accountUUID).toCharArray()); KeyStore keyStore = KeyStore.Builder .newInstance("pkcs12", null, INSTANCE.getFileStreamPath(accountUUID), protection) .getKeyStore(); registry.register( new Scheme("https", new SSLSocketFactory(keyStore, getPassword(accountUUID)), 443)); } else { Log.d(TAG, "Create regular SSL factory"); registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); } // Use "insecure" socket factory. SSLSocketFactory sf = new SSLSocketFactory(SSLUtils.getSSLSocketFactory(true)); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Register the httpts scheme with our factory registry.register(new Scheme("httpts", sf, 443)); HttpParams params = new BasicHttpParams(); params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, SyncManager.sConnPerRoute); clientConnectionManager = new ThreadSafeClientConnManager(params, registry); clientConnectionManagerMap.put(accountUUID, clientConnectionManager); } catch (Exception e) { Log.e(TAG, "Error with keystore or something related!", e); throw new IllegalStateException(e); } } return clientConnectionManager; }
From source file:com.android.exchange.ExchangeService.java
static public synchronized EmailClientConnectionManager getClientConnectionManager() { if (sClientConnectionManager == null) { // After two tries, kill the process. Most likely, this will happen in the background // The service will restart itself after about 5 seconds if (sClientConnectionManagerShutdownCount > MAX_CLIENT_CONNECTION_MANAGER_SHUTDOWNS) { alwaysLog("Shutting down process to unblock threads"); Process.killProcess(Process.myPid()); }/* w ww . j a v a 2 s . c o m*/ HttpParams params = new BasicHttpParams(); params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, sConnPerRoute); sClientConnectionManager = EmailClientConnectionManager.newInstance(params); } // Null is a valid return result if we get an exception return sClientConnectionManager; }
From source file:cn.com.loopj.android.http.AsyncHttpClient.java
/** * Sets the Proxy by it's hostname and port * * @param hostname the hostname (IP or DNS name) * @param port the port number. -1 indicates the scheme default port. *//*from w ww. ja v a2 s. c o m*/ public void setProxy(String hostname, int port) { final HttpHost proxy = new HttpHost(hostname, port); final HttpParams httpParams = this.httpClient.getParams(); httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }
From source file:cn.com.loopj.android.http.AsyncHttpClient.java
/** * Sets the Proxy by it's hostname,port,username and password * * @param hostname the hostname (IP or DNS name) * @param port the port number. -1 indicates the scheme default port. * @param username the username/*w w w.j a v a 2 s . c o m*/ * @param password the password */ public void setProxy(String hostname, int port, String username, String password) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port), new UsernamePasswordCredentials(username, password)); final HttpHost proxy = new HttpHost(hostname, port); final HttpParams httpParams = this.httpClient.getParams(); httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }
From source file:org.dasein.cloud.atmos.AtmosMethod.java
protected @Nonnull HttpClient getClient(String endpoint) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new CloudException("No context was specified for this request"); }// ww w .j a v a2 s. c o m boolean ssl = endpoint.startsWith("https"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } return new DefaultHttpClient(params); }
From source file:com.akop.bach.parser.PsnEuParser.java
@Override protected boolean onAuthenticate(BasicAccount account) throws IOException, ParserException { PsnAccount psnAccount = (PsnAccount) account; String password = psnAccount.getPassword(); if (password == null) throw new ParserException(mContext.getString(R.string.decryption_error)); HttpParams params = mHttpClient.getParams(); // Prepare POSTDATA List<NameValuePair> inputs = new ArrayList<NameValuePair>(3); addValue(inputs, "j_username", psnAccount.getEmailAddress()); addValue(inputs, "j_password", password); addValue(inputs, "returnURL", URL_RETURN_LOGIN); // Enable redirection (max 1) params.setParameter("http.protocol.max-redirects", 3); // 1. Post authentication data String page = getResponse(URL_LOGIN, inputs); // Disable redirection params.setParameter("http.protocol.max-redirects", 1); // Get redirection URL Matcher m = PATTERN_SIGN_OUT_LINK.matcher(page); if (!m.find()) { if (App.getConfig().logToConsole()) App.logv("onAuthEU: Redir URL not found"); String outageMessage;/* w w w .jav a 2 s . co m*/ if ((outageMessage = getOutageMessage(page)) != null) throw new ParserException(outageMessage); return false; } return true; }