Using Java to get HTTP response headers and request resources

Source: Internet
Author: User

Code instance
Import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import Java.io.file;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.InputStreamReader; Import Java.io.reader;import java.net.urisyntaxexception;import Java.net.url;import Java.net.urlconnection;import Java.util.iterator;import java.util.list;import java.util.map;import Java.util.map.entry;import java.util.Set; public class Urltest {public static void main (string[] args) throws URISyntaxException {InputStream Inputstream=null;try { Create a URL object, for example: Baidu search China good sound//wd The value of the keyword is the UTF-8 encoding for "good sound in China", and you can encode the character using Urlencoder string str= "http://www.baidu.com/s?wd=%E4 %b8%ad%e5%9b%bd%e5%a5%bd%e5%a3%b0%e9%9f%b3 "+" &rsv_spt=1&issp=1&f=8&rsv_bp=0&rsv_idx=2& Ie=utf-8&tn=baiduhome_pg "+" &rsv_enter=1&inputt=1498 "; URL url = new URL (str);//Create URLConnection object URLConnection openconnection = Url.openconnection ();//encoding type string encoding= null;//Print the response header section below System.out.println ("-----------The response header begins-----------"); map<string, list<string>> headerfields = Openconnection.getheaderfields (); set<entry<string, list<string>>> entryset = Headerfields.entryset (); Iterator<Entry<String, List<string>>> iterator = Entryset.iterator (); while (Iterator.hasnext ()) {entry<string, list< String>> next = Iterator.next (); String key = Next.getkey (); list<string> value = Next.getvalue (); String string = Value.tostring (); System.out.println (key+ ":" +string), if ("Content-type". Equals (key)) {int indexOf = String.IndexOf ("charset="); encoding = string.substring (Indexof+8,string.length ()-1);}} SYSTEM.OUT.PRINTLN ("-----------Response header End-----------");//Gets the input stream of the URLConnection object inputstream= Openconnection.getinputstream ();//read stream via IO, write file int c;int count=0; File File=new file ("baiduosc.html"); FileOutputStream FileOutputStream = new FileOutputStream (file); Bufferedoutputstream outputstream = new Bufferedoutputstream (fileoutputstream); Inputstream=new BUFFEREDINPUtstream (InputStream); Reader InputStreamReader = new InputStreamReader (inputstream,encoding); while ((C=inputstreamreader.read ())!=-1) { Outputstream.write (c); count++;} Inputstreamreader.close (); Outputstream.close (); SYSTEM.OUT.PRINTLN (the size of "file" +file.getname () + "is" +math.ceil (count/1024.0) + "KB"); System.out.println ("Download End");} catch (IOException e) {System.err.println ("Cannot Download"),} finally {if (inputstream!=null) {try {inputstream.close ();} catch ( Exception ex) {//Not processed}}}}
Running an instance
-----------response header starts-----------bdpagetype:[3]transfer-encoding:[chunked]null:[http/1.1 ok]server:[bws/1.1]cxy_ex : [1438852608+2445156729+D41D8CD98F00B204E9800998ECF8427E]BDQID:[0XC8CF935400001D62]CONNECTION:[KEEP-ALIVE]P3P: [cp= "OTI DSP cor IVA our ind com", cp= "OTI DSP cor IVA our ind com"] Date:[thu, 09:16:48 gmt]x-ua-compatible:[ie=edge,chrome=1]cache-control:[private]cxy_all:[baiduhome_pg+ 66d9c0f29a9055c1f190fe638dacaa45]set-cookie:[h_ps_pssid=11193_16469_1438_12867_14668_16520_16513_16662_16424_ 16515_15459_12141_13932_16721; path=/; Domain=.baidu.com, bdsvrtm=187; path=/, bd_ck_sam=1;path=/, bdrcvfr[fewj1vr5u3d]=mk3slvn4hkm; path=/; Domain=.baidu.com, pstm=1438852608; Expires=thu, 31-dec-37 23:55:55 GMT; max-age=2147483647; path=/; Domain=.baidu.com, bidupsid=5dae500615a53e18fdb62639c686768b; Expires=thu, 31-dec-37 23:55:55 GMT; max-age=2147483647; path=/; Domain=.baidu.com, baiduid=5dae500615a53e18fdb62639c686768b:fg=1; Expires=thu, 31-dec-37 23:55:55 GMT; Max-age=2147483647; path=/; domain=.baidu.com]vary:[accept-encoding]bduserid:[0]x-powered-by:[hphp]content-type:[text/html;charset=utf-8]- ----------response header ends-----------file baiduosc.html the size of 491.0kb download ends




Using Java to get HTTP response headers and request resources

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.