Dica rápida: como fazer conexão HTTPClient
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/feltexco/public_html/felix/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/feltexco/public_html/felix/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/feltexco/public_html/felix/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
Dica rápida: como fazer conexão HTTPClient
Olá amigos. Hoje vamos conhecer o HTTpClient. Quando precisamos acessar dados pela via protocolo HTTP sem utilizar o browser precisamos implementar uma solução dinâmica e totalmente controlada por nossa aplicação.
Mãos à obra!
1. Acesso Básico
O projeto de hoje consiste em acessar um site na internet e ler todo o conteúdo textual e exibir esses dados na console do nosso programa.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | package br.com.feltex.http; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; public class ConexaoHTTP { public static void main(String[] args) { try { URL url = new URL("http://www.feltex.com.br/felix"); BufferedReader in = new BufferedReader(new InputStreamReader( url.openStream())); String str = ""; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (Exception e) { e.printStackTrace(); } } } |
Você terá como resultado todo o código HTML da página buscada. O passo seguinte é você fazer o tratamento que desejar.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | a#nbar_downArr.bottom{border-bottom-color:#23ADCF;} #nbar_downArr{margin-top:4px;} #notificationbar .nbar_topwrap .nbar_msg{font-size:12px;color:#f3eeee; } #notificationbar .nbar_topwrap .nbar_button{font-size:12px;color:#fbf8e6;background:#57380b} #notificationbar .nbar_extendmsg .nbar_extendmsg_txt{font-size:12px;color:#ffffff; } #notificationbar .nbar_extendmsg .nbar_extendmsg_btn{font-size:12px;color:#fde8c0;background:#62562e} #notificationbar .nbar_extendmsg .nbar_extendmsg_img{width:150px;height:150px;border-width:2px;border-color:#fff;} </style> <div id="notificationbar" class="notificationbar_options"> <div class="nbar_wrapper top"> <div class="nbar_topwrap"> <div class="nbar_msg nbar_topitem">Get my Subscription</div> <a class="nbar_button nbar_topitem" href="#" target="_blank">Click here</a> <div class="nbar_sociallinks"> <a href="https://www.facebook.com/" class="fb" title="facebook" target="_blank" ></a> <a href="https://twitter.com/" class="tw" title="twitter" target="_blank" ></a> <a href="http://www.linkedin.com/" class="ld" title="linkedin" target="_blank" ></a> <a href="http://www.google.com/" class="gp" title="google+" target="_blank" ></a> <iframe class="fblike" src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.feltex.com.br%2Ffelix%2Fconfigurar-datasource-servidor-wildfly%2F&layout=button_count&show_faces=false&width=60&action=like&font=segoe+ui&colorscheme=light&height=21" scrolling="no" frameborder="0" allowTransparency="true"></iframe> </div> <a href="JavaScript:void(0);" title="show/hide" class="nbar_plusminus"></a> </div> <div class="nbar_extendmsg template-3"> <div class="nbar_exmsg"> <img src="http://www.feltex.com.br/felix/wp-content/themes/biznez-lite/SketchBoard/functions/modules/nbar//inc/images/default.jpg" class="nbar_extendmsg_img" alt="biznez" /> <div class="nbar_extendmsg_wrap"> <div class="nbar_extendmsg_txt">Extend Message goes here..</div> <a href="#" target="_blank" class="nbar_extendmsg_btn">More..</a> </div> <div style="clear:both;"></div> </div> </div> </div> <a id="nbar_downArr" class="top" href="JavaScript:void(0);" >+</a> </div> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('body').prepend('<div class="notification_push"></div>'); jQuery("#notificationbar").notificationbar({ 'defaultstate': 'open', 'staytime': '10000', 'exmsgstate': 'open', 'exmsgopentm':'4000', 'exmsgclosetm':'4000', 'disablecmsg':'no' }); }); </script> <!-- Notification Bar PRO Ends Here --> <script type="text/javascript"> var addthis_config = {"data_track_clickback":false,"data_track_addressbar":false,"data_track_textcopy":false,"ui_atversion":"300"}; var addthis_product = 'wpp-4.0'; </script><script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-537584a566c0ddb2"></script><!--wp_footer--></body> </html> <!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/ Served from: www.feltex.com.br @ 2015-01-15 18:00:25 by W3 Total Cache --> |
2. Acesso utilizando um Proxy com autenticação
Se na rede onde você se encontra é necessário o uso de proxy com autenticação você deve usar o exemplo da seguinte forma:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package br.com.feltex.http; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; public class ConexaoHTTP { public static void main(String[] args) { try { //Configuração do seu proxy System.setProperty("proxySet", "true"); System.setProperty("http.proxyHost", "proxy.feltex.com.br"); System.setProperty("proxy.authentication.username", "usuario"); System.setProperty("proxy.authentication.password", "senha"); System.setProperty("http.proxyPort", "80"); URL url = new URL("http://www.feltex.com.br/felix"); BufferedReader in = new BufferedReader(new InputStreamReader( url.openStream())); String str = ""; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (Exception e) { e.printStackTrace(); } } } |
3. Conclusão
Então é isso amigos. Esta é uma das formas de acessar conteúdo na web sem precisar utilizar um browser. Isto é o início para nós implementarmos o nosso próprio browser com a linguagem Java.
Por hoje é só meus amigos e Vida que segue!
Links relacionados
Dica Rápida: Leitura de PDF com PDFBox
Dica rápida: Aprenda como Descompactar Arquivo com o JavaZip
Dica rápida: Aprenda como Compactar Arquivo com o JavaZip
Deixe um comentário
Você precisa fazer o login para publicar um comentário.