Send HTTP packets in Java

Source: Internet
Author: User

 

Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstream; import Java. io. inputstreamreader; import java.net. httpurlconnection; import java.net. URL; public class WebClient {public static string getwebcontent (string urlstring, final string charset, int timeout) throws ioexception {If (urlstring = NULL | urlstring. length () = 0) {return NULL;} urlstring = (urlstring. startswith ("HTTP: // ") | Urlstring. startswith (" https ://"))? Urlstring: ("http: //" + urlstring ). intern (); Url url = new URL (urlstring); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setrequestproperty ("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0 ;. net CLR 1.1.4322 ;. net CLR 2.0.50727) "); // adds a header to simulate the browser to prevent blocking Conn. setrequestproperty ("accept", "text/html"); // only the text/html type is accepted. Of course, images, PDF, and */* can be accepted, that is, tomcat. In/CONF/Web, define the conn. setconnecttimeout (timeout); try {If (conn. getresponsecode ()! = Httpurlconnection. http_ OK) {return NULL ;}} catch (ioexception e) {e. printstacktrace (); return NULL;} inputstream input = Conn. getinputstream (); bufferedreader reader = new bufferedreader (New inputstreamreader (input, charset); string line = NULL; stringbuffer sb = new stringbuffer (); While (line = reader. readline ())! = NULL) {sb. append (Line). append ("/R/N");} If (reader! = NULL) {reader. Close () ;}if (Conn! = NULL) {Conn. disconnect ();} return sb. tostring ();} public static string getwebcontent (string urlstring) throws ioexception {return getwebcontent (urlstring, "iso-8859-1", 5000);} public static void main (string [] ARGs) throws ioexception {string S = getwebcontent ("http://www.sina.com"); s = new string (S. getbytes ("iso-8859-1"), "gb2312"); system. out. println (s );}}
  3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.