List of usage examples for org.apache.http.params HttpProtocolParams setContentCharset
public static void setContentCharset(HttpParams httpParams, String str)
From source file:com.google.appengine.tck.endpoints.support.EndPointClient.java
/** * Get client./*from w w w.jav a 2s. c o m*/ * * @return the client */ private synchronized HttpClient getClient() { if (client == null) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout()); HttpProtocolParams.setVersion(params, getHttpVersion()); HttpProtocolParams.setContentCharset(params, getContentCharset()); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", getPort(), getPlainFactory())); schemeRegistry.register(new Scheme("https", getSslPort(), getSslFactory())); ClientConnectionManager ccm = createClientConnectionManager(schemeRegistry); client = createClient(ccm, params); } return client; }
From source file:com.networkmanagerapp.JSONBackgroundDownloaderService.java
/** * Delegate method to run the specified intent in another thread. * @param arg0 The intent to run in the background *///from w w w .j a va 2s . c om @Override protected void onHandleIntent(Intent arg0) { mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); showNotification(); String filename = arg0.getStringExtra("FILENAME"); String jsonFile = arg0.getStringExtra("JSONFILE"); try { String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference", ""); Log.d("password", password); String ip = PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference", "192.168.1.1"); String enc = URLEncoder.encode(ip, "UTF-8"); String scriptUrl = "http://" + enc + ":1080" + filename; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(params, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 20000; HttpConnectionParams.setSoTimeout(params, timeoutSocket); HttpHost targetHost = new HttpHost(enc, 1080, "http"); DefaultHttpClient client = new DefaultHttpClient(params); client.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("root", password)); HttpGet request = new HttpGet(scriptUrl); HttpResponse response = client.execute(targetHost, request); Log.d("JBDS", response.getStatusLine().toString()); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder str = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { str.append(line + "\n"); } in.close(); if (str.toString().equals("Success\n")) { String xmlUrl = "http://" + enc + ":1080/json" + jsonFile; request = new HttpGet(xmlUrl); HttpResponse jsonData = client.execute(targetHost, request); in = jsonData.getEntity().getContent(); reader = new BufferedReader(new InputStreamReader(in)); str = new StringBuilder(); line = null; while ((line = reader.readLine()) != null) { str.append(line + "\n"); } in.close(); FileOutputStream fos = openFileOutput(jsonFile.substring(1), Context.MODE_PRIVATE); fos.write(str.toString().getBytes()); fos.close(); } } catch (MalformedURLException ex) { Log.e("NETWORKMANAGER_XBD_MUE", ex.getMessage()); } catch (IOException e) { try { Log.e("NETWORK_MANAGER_XBD_IOE", e.getMessage()); StackTraceElement[] st = e.getStackTrace(); for (int i = 0; i < st.length; i++) { Log.e("NETWORK_MANAGER_XBD_IOE", st[i].toString()); } } catch (NullPointerException ex) { Log.e("Network_manager_xbd_npe", ex.getLocalizedMessage()); } } finally { mNM.cancel(R.string.download_service_started); Intent bci = new Intent(NEW_DATA_AVAILABLE); sendBroadcast(bci); stopSelf(); } }
From source file:eu.musesproject.client.connectionmanager.TLSManager.java
/** * Sreate https client object//from w ww.j a va 2 s .c o m * @return DefaultHttpClient */ private HttpClient createHttpClient() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET); HttpProtocolParams.setUseExpectContinue(params, true); SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), HTTP_PORT)); schReg.register(new Scheme("https", (SocketFactory) newSslSocketFactory(), HTTPS_PORT)); ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg); return new DefaultHttpClient(conMgr, params); }
From source file:org.apache.hadoop.gateway.jetty.SslSocketTest.java
@Ignore @Test// www . j ava2 s . com public void testSsl() throws IOException, InterruptedException { SslServer server = new SslServer(); Thread thread = new Thread(server); thread.start(); server.waitUntilReady(); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); params.setBooleanParameter("http.protocol.expect-continue", false); SSLSocketFactory sslsocketfactory = SSLSocketFactory.getSocketFactory(); SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(params); sslsocket.connect(new InetSocketAddress("localhost", 9999)); OutputStream outputstream = sslsocket.getOutputStream(); OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream); BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter); bufferedwriter.write("HELLO\n"); bufferedwriter.flush(); }
From source file:org.teleal.cling.transport.impl.apache.StreamClientImpl.java
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException { this.configuration = configuration; ConnManagerParams.setMaxTotalConnections(globalParams, getConfiguration().getMaxTotalConnections()); HttpConnectionParams.setConnectionTimeout(globalParams, getConfiguration().getConnectionTimeoutSeconds() * 1000); HttpConnectionParams.setSoTimeout(globalParams, getConfiguration().getDataReadTimeoutSeconds() * 1000); HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset()); if (getConfiguration().getSocketBufferSize() != -1) { // Android configuration will set this to 8192 as its httpclient is // based//ww w. j av a 2 s . com // on a random pre 4.0.1 snapshot whose BasicHttpParams do not set a // default value for socket buffer size. // This will also avoid OOM on the HTC Thunderbolt where default // size is 2Mb (!): // http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize()); } HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled()); // This is a pretty stupid API... // https://issues.apache.org/jira/browse/HTTPCLIENT-805 SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // The // 80 // here // is... // useless clientConnectionManager = new ThreadSafeClientConnManager(globalParams, registry); httpClient = new DefaultHttpClient(clientConnectionManager, globalParams); if (getConfiguration().getRequestRetryCount() != -1) { httpClient.setHttpRequestRetryHandler( new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false)); } /* * // TODO: Ugh! And it turns out that by default it doesn't even use * persistent connections properly! * * @Override protected ConnectionReuseStrategy * createConnectionReuseStrategy() { return new * NoConnectionReuseStrategy(); } * * @Override protected ConnectionKeepAliveStrategy * createConnectionKeepAliveStrategy() { return new * ConnectionKeepAliveStrategy() { public long * getKeepAliveDuration(HttpResponse httpResponse, HttpContext * httpContext) { return 0; } }; } * httpClient.removeRequestInterceptorByClass(RequestConnControl.class); */ }
From source file:edu.upc.tutorial.jaxrs.android.data.LibraryResteasyClient.java
private LibraryClient getLibraryClient() { String requestURI = LibraryApplication.getRequestURI(context); if (client == null || !requestURI.equals(lastRequestURI)) { BasicHttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET); HttpProtocolParams.setUseExpectContinue(params, false); client = ProxyFactory.create(LibraryClient.class, requestURI, new ApacheHttpClient4Executor(params)); lastRequestURI = requestURI;/* w w w.jav a 2s . c o m*/ } return client; }
From source file:com.devoteam.srit.xmlloader.http.test.HttpLoaderClient.java
protected void createRequest(int i) throws Exception { // Create a HTTP message object corresponding to the string message HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setHttpElementCharset(params, "UTF-8"); HttpProtocolParams.setContentCharset(params, "text"); HttpProtocolParams.setUserAgent(params, "XmlLoader"); HttpProtocolParams.setUseExpectContinue(params, true); http.sendRequest("GET", "D:/XMLloader/testPileHttp/src/test/HttpLoader/" + i, params); }
From source file:com.shwy.bestjoy.utils.AndroidHttpClient.java
/** * Create a new HttpClient with reasonable defaults (which you can update). * * @param userAgent to report in your HTTP requests. * @return AndroidHttpClient for you to use for all your requests. *//*from w w w . j a v a2s.c o m*/ public static HttpClient newInstance(String userAgent) { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sslSocketFactory = new SSLSocketFactoryEx(trustStore); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); // Default connection and socket timeout of 20 seconds. Tweak to taste. HttpConnectionParams.setConnectionTimeout(params, 60 * 1000); HttpConnectionParams.setSoTimeout(params, 60 * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); // Don't handle redirects -- return them to the caller. Our code // often wants to re-POST after a redirect, which we must do ourselves. HttpClientParams.setRedirecting(params, true); // Set the specified user agent and register standard protocols. HttpProtocolParams.setUserAgent(params, userAgent); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry); // We use a factory method to modify superclass initialization // parameters without the funny call-a-static-method dance. return new AndroidHttpClient(manager, params); } catch (KeyStoreException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return new DefaultHttpClient(); }
From source file:at.diamonddogs.net.WebClientDefaultHttpClient.java
/** * Default {@link WebClient} constructor * //from w w w. j a va 2s . com * @param context * a {@link Context} object */ public WebClientDefaultHttpClient(Context context) { super(context); SSLSocketFactory sslSocketFactory = SSLHelper.getInstance().SSL_FACTORY_APACHE; if (sslSocketFactory != null) { sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sslSocketFactory, 443)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); httpClient = new DefaultHttpClient(ccm, params); } else { httpClient = new DefaultHttpClient(); } httpClient.setHttpRequestRetryHandler(this); if (followProtocolRedirect) { httpClient.setRedirectHandler(this); } }
From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java
public RSSFeed getRSSFeed(String channelTitle, String channelUrl, String filter) { // Decode url link try {//from w ww. ja v a2 s. c o m channelUrl = URLDecoder.decode(channelUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { Log.e("Debug", "RSSFeedParser - decoding error: " + e.toString()); } // Parse url Uri uri = uri = Uri.parse(channelUrl); ; int event; String text = null; String torrent = null; boolean header = true; // TODO delete itemCount, as it's not really used this.itemCount = 0; HttpResponse httpResponse; DefaultHttpClient httpclient; XmlPullParserFactory xmlFactoryObject; XmlPullParser xmlParser = null; 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); RSSFeed rssFeed = new RSSFeed(); rssFeed.setChannelTitle(channelTitle); rssFeed.setChannelLink(channelUrl); httpclient = null; try { // Making HTTP request HttpHost targetHost = new HttpHost(uri.getAuthority()); // httpclient = new DefaultHttpClient(httpParameters); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); // AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); // // httpclient.getCredentialsProvider().setCredentials(authScope, credentials); // set http parameters HttpGet httpget = new HttpGet(channelUrl); httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); xmlFactoryObject = XmlPullParserFactory.newInstance(); xmlParser = xmlFactoryObject.newPullParser(); xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); xmlParser.setInput(is, null); event = xmlParser.getEventType(); // Get Channel info String name; RSSFeedItem item = null; ArrayList<RSSFeedItem> items = new ArrayList<RSSFeedItem>(); // Get items while (event != XmlPullParser.END_DOCUMENT) { name = xmlParser.getName(); switch (event) { case XmlPullParser.START_TAG: if (name != null && name.equals("item")) { header = false; item = new RSSFeedItem(); itemCount = itemCount + 1; } try { for (int i = 0; i < xmlParser.getAttributeCount(); i++) { if (xmlParser.getAttributeName(i).equals("url")) { torrent = xmlParser.getAttributeValue(i); if (torrent != null) { torrent = Uri.decode(URLEncoder.encode(torrent, "UTF-8")); } break; } } } catch (Exception e) { } break; case XmlPullParser.TEXT: text = xmlParser.getText(); break; case XmlPullParser.END_TAG: if (name.equals("title")) { if (!header) { item.setTitle(text); // Log.d("Debug", "PARSER - Title: " + text); } } else if (name.equals("description")) { if (header) { // Log.d("Debug", "Channel Description: " + text); } else { item.setDescription(text); // Log.d("Debug", "Description: " + text); } } else if (name.equals("link")) { if (!header) { item.setLink(text); // Log.d("Debug", "Link: " + text); } } else if (name.equals("pubDate")) { // Set item pubDate if (item != null) { item.setPubDate(text); } } else if (name.equals("enclosure")) { item.setTorrentUrl(torrent); // Log.d("Debug", "Enclosure: " + torrent); } else if (name.equals("item") && !header) { if (items != null & item != null) { // Fix torrent url for no-standard rss feeds if (torrent == null) { String link = item.getLink(); if (link != null) { link = Uri.decode(URLEncoder.encode(link, "UTF-8")); } item.setTorrentUrl(link); } items.add(item); } } break; } event = xmlParser.next(); // if (!header) { // items.add(item); // } } // Filter items // Log.e("Debug", "RSSFeedParser - filter: >" + filter + "<"); if (filter != null && !filter.equals("")) { Iterator iterator = items.iterator(); while (iterator.hasNext()) { item = (RSSFeedItem) iterator.next(); // If link doesn't match filter, remove it // Log.e("Debug", "RSSFeedParser - item no filter: >" + item.getTitle() + "<"); Pattern patter = Pattern.compile(filter); Matcher matcher = patter.matcher(item.getTitle()); // get a matcher object if (!(matcher.find())) { iterator.remove(); } } } rssFeed.setItems(items); rssFeed.setItemCount(itemCount); rssFeed.setChannelPubDate(items.get(0).getPubDate()); rssFeed.setResultOk(true); is.close(); } catch (Exception e) { Log.e("Debug", "RSSFeedParser - : " + e.toString()); rssFeed.setResultOk(false); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } // return JSON String return rssFeed; }