List of usage examples for org.apache.http.params HttpProtocolParams setContentCharset
public static void setContentCharset(HttpParams httpParams, String str)
From source file:org.jets3t.service.utils.RestUtils.java
/** * Default Http parameters got from the DefaultHttpClient implementation. * * @return/*from w w w .j a va 2 s.c om*/ * Default HTTP connection parameters */ public static HttpParams createDefaultHttpParams() { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSocketBufferSize(params, 8192); // determine the release version from packaged version info final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", HttpClient.class.getClassLoader()); final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; HttpProtocolParams.setUserAgent(params, "Apache-HttpClient/" + release + " (java 1.5)"); return params; }
From source file:de.uni_koblenz_landau.apow.helper.SyncHelper.java
/** * Creates a HTTPClient for usage with self signed SSL certificates. * /* w w w . ja va2 s . c om*/ * Sources: * http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https * http://havrl.blogspot.de/2013/08/synchronization-algorithm-for.html * * @return HTTPClient */ private static HttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SelfSignedSSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:fr.eolya.utils.http.HttpLoader.java
private HttpParams getHttpParams() { HttpParams httpParams = new BasicHttpParams(); // connection HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeOut); HttpConnectionParams.setSoTimeout(httpParams, sockeTimeOut); // protocol/* w w w .j ava 2 s .c o m*/ HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, "utf-8"); // user-agent if (!StringUtils.isEmpty(userAgent)) { httpParams.setParameter(CoreProtocolPNames.USER_AGENT, userAgent); } // redirect httpParams.setParameter("http.protocol.handle-redirects", followRedirect); return httpParams; }
From source file:org.openmeetings.app.sip.xmlrpc.OpenXGHttpClient.java
public HttpClient getHttpClient() { try {/* w w w. j a va 2 s. c o m*/ SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", 443, sf)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.github.vseguip.sweet.rest.SugarRestAPI.java
/** * Get an HttpConnection object. Will create a new one if needed. * //www . ja v a 2s. c om * @return A defualt HTTP connection object */ private HttpClient getConnection() { if (mHttpClient == null) { // registers schemes for both http and https HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUseExpectContinue(params, false); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_OPS); HttpConnectionParams.setSoTimeout(params, TIMEOUT_OPS); ConnManagerParams.setTimeout(params, TIMEOUT_OPS); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory(); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); if (!mNoCertValidation) registry.register(new Scheme("https", sslSocketFactory, 443)); else registry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); mHttpClient = new DefaultHttpClient(manager, params); } return mHttpClient; }
From source file:org.dasein.cloud.rackspace.AbstractMethod.java
private @Nonnull HttpClient getClient() throws CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new CloudException("No context was provided for this request"); }/*from w ww . ja v a 2 s. c om*/ String endpoint = ctx.getEndpoint(); boolean ssl = (endpoint != null && endpoint.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.dasein.cloud.zimory.ZimoryMethod.java
private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new NoContextException(); }//from w ww. j a v a 2s.c o m boolean ssl = uri.getScheme().startsWith("https"); int targetPort = uri.getPort(); if (targetPort < 1) { targetPort = (ssl ? 443 : 80); } HttpParams params = new BasicHttpParams(); SchemeRegistry registry = new SchemeRegistry(); try { registry.register( new Scheme(ssl ? "https" : "http", targetPort, new X509SSLSocketFactory(new X509Store(ctx)))); } catch (KeyManagementException e) { e.printStackTrace(); throw new InternalException(e); } catch (UnrecoverableKeyException e) { e.printStackTrace(); throw new InternalException(e); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new InternalException(e); } catch (KeyStoreException e) { e.printStackTrace(); throw new InternalException(e); } HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, ""); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000); 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")); } } ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry); return new DefaultHttpClient(ccm, params); }
From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java
/** * This method takes the SOAP AuthnRequest, sends it to the IdP, and retrieves * the result. This method does not process the result. * //from www .j a va2s. c o m * @param samlSession SAML session * @param authnState * @return true, if successful */ private boolean getSOAPResponse(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) { this.logger.debug("Step 4 of 5: Get SOAP response from IDP"); String result = null; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); params.setParameter("SOAPAction", "urn:liberty:ssos:2006-08:AuthnRequest"); HttpClient client = new DefaultHttpClient(params); try { logger.debug("Getting SOAP response from {} with POST body:\n{}", authnState.getIdpEndpoint(), authnState.getModifiedSOAPRequest()); setupIdPClientConnection(client, samlSession, authnState); HttpPost method = new HttpPost(authnState.getIdpEndpoint()); method.setHeader("Content-Type", "text/xml"); StringEntity postData = new StringEntity(authnState.getModifiedSOAPRequest(), HTTP.UTF_8); method.setEntity(postData); HttpResponse httpResponse = client.execute(method); int resultCode = httpResponse.getStatusLine().getStatusCode(); if (resultCode >= HttpStatus.SC_OK && resultCode < 300) { HttpEntity httpEntity = httpResponse.getEntity(); ByteArrayOutputStream output = new ByteArrayOutputStream(); httpEntity.writeTo(output); result = output.toString(); logger.debug("Got SOAP response:\n{}", result); authnState.setSoapResponse(result); return true; } logger.error("Unsupported HTTP result code when retrieving the resource: " + resultCode + "."); throw new DelegatedAuthenticationRuntimeException( "Unsupported HTTP result code when retrieving the resource: " + resultCode + "."); } catch (Exception ex) { logger.error("Exception caught when trying to retrieve the resource.", ex); throw new DelegatedAuthenticationRuntimeException( "Exception caught when trying to retrieve the resource.", ex); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public String getNewCookie() throws JSONParserStatusCodeException { String url = "login"; // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }/*from w w w. j av a 2 s .c o m*/ String cookieString = null; HttpResponse httpResponse; DefaultHttpClient httpclient; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(hostname, port, protocol); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); // Set http parameters httpclient.setParams(httpParameters); try { // AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // // UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); // // httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpPost httpget = new HttpPost(url); // // In order to pass the username and password we must set the pair name value List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", this.username)); nvps.add(new BasicNameValuePair("password", this.password)); httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode == 200) { // Save cookie List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue() + "; domain=" + cookies.get(0).getDomain(); cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue(); } } if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } catch (Exception e) { Log.e("Debug", "Exception " + e.toString()); } if (cookieString == null) { cookieString = ""; } return cookieString; }
From source file:org.nla.tarotdroid.lib.ui.GameSetHistoryActivity.java
@Override public void onCreate(final Bundle savedInstanceState) { try {/*from ww w . j av a 2 s .c om*/ super.onCreate(savedInstanceState); // facebook lifecycle objects this.uiHelper = new UiLifecycleHelper(this, facebookSessionStatusCallback); this.uiHelper.onCreate(savedInstanceState); this.auditEvent(); // initialize progress dialog this.progressDialog = new ProgressDialog(this); this.progressDialog.setCanceledOnTouchOutside(false); this.httpClient = new DefaultHttpClient(); HttpParams httpParams = new BasicHttpParams(); HttpProtocolParams.setContentCharset(httpParams, Charsets.UTF_8.toString()); httpClient.setParams(httpParams); // initialize bluetooth this.bluetoothHelper = AppContext.getApplication().getBluetoothHelper(); this.bluetoothHelper.setActivity(this); // set excuse as background image this.getListView().setCacheColorHint(0); this.getListView().setBackgroundResource(R.drawable.img_excuse); // set action bar properties this.setTitle(); this.registerForContextMenu(this.getListView()); // set internal properties this.tempExcelFilePath = null; this.tempGameSet = null; // wait for the dal to be initiated to refresh the game sets if (AppContext.getApplication().getLoadDalTask().getStatus() == AsyncTask.Status.RUNNING) { AppContext.getApplication().getLoadDalTask().showDialogOnActivity(this, this.getResources().getString(R.string.msgGameSetsRetrieval)); AppContext.getApplication().getLoadDalTask().setCallback(new IAsyncCallback<String>() { @Override public void execute(String result, Exception e) { // TODO Check exception if (result != null && result.toString().length() > 0) { UIHelper.showSimpleRichTextDialog(GameSetHistoryActivity.this, result, "Erreur de chargement"); } GameSetHistoryActivity.this.refresh(); } }); } // refresh the game sets else { this.refresh(); } Object currentRunningTask = getLastNonConfigurationInstance(); if (currentRunningTask != null) { if (currentRunningTask instanceof UpSyncGameSetTask) { UpSyncGameSetTask task = (UpSyncGameSetTask) currentRunningTask; task.attach(this); } else if (currentRunningTask instanceof PostGameSetLinkOnFacebookWallTask) { PostGameSetLinkOnFacebookWallTask task = (PostGameSetLinkOnFacebookWallTask) currentRunningTask; task.attach(this); } } this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long arg3) { onListItemClick(pos); return false; } }); this.getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) { onListItemClick(pos); } }); } catch (Exception e) { AuditHelper.auditError(ErrorTypes.gameSetHistoryActivityError, e, this); } }