Java发送Http请求,解析html返回

首先,向一个Web站点发送POST请求只需要简单的几步: 
注意,这里不需要导入任何第三方包 

[java]  view plain copy
  1. package com.test;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.io.OutputStreamWriter;  
  8. import java.net.URL;  
  9. import java.net.URLConnection;  
  10.   
  11. public class TestPost {  
  12.   
  13.     public static void testPost() throws IOException {  
  14.   
  15.         /** 
  16.          * 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如: // Using 
  17.          *  java.net.URL and //java.net.URLConnection 
  18.          */  
  19.         URL url = new URL("http://www.faircanton.com/message/check.asp");  
  20.         URLConnection connection = url.openConnection();  
  21.         /** 
  22.          * 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。 
  23.          * 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做: 
  24.          */  
  25.         connection.setDoOutput(true);  
  26.         /** 
  27.          * 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ... 
  28.          */  
  29.         OutputStreamWriter out = new OutputStreamWriter(connection  
  30.                 .getOutputStream(), "8859_1");  
  31.         out.write("username=kevin&password=*********"); //post的关键所在!  
  32.         // remember to clean up  
  33.         out.flush();  
  34.         out.close();  
  35.         /** 
  36.          * 这样就可以发送一个看起来象这样的POST:  
  37.          * POST /jobsearch/jobsearch.cgi HTTP 1.0 ACCEPT: 
  38.          * text/plain Content-type: application/x-www-form-urlencoded 
  39.          * Content-length: 99 username=bob password=someword 
  40.          */  
  41.         // 一旦发送成功,用以下方法就可以得到服务器的回应:  
  42.         String sCurrentLine;  
  43.         String sTotalString;  
  44.         sCurrentLine = "";  
  45.         sTotalString = "";  
  46.         InputStream l_urlStream;  
  47.         l_urlStream = connection.getInputStream();  
  48.         // 传说中的三层包装阿!  
  49.         BufferedReader l_reader = new BufferedReader(new InputStreamReader(  
  50.                 l_urlStream));  
  51.         while ((sCurrentLine = l_reader.readLine()) != null) {  
  52.             sTotalString += sCurrentLine + "/r/n";  
  53.   
  54.         }  
  55.         System.out.println(sTotalString);  
  56.     }  
  57.   
  58.     public static void main(String[] args) throws IOException {  
  59.   
  60.         testPost();  
  61.   
  62.     }  
  63.   
  64. }  



执行的结果:(果真是返回了验证后的html阿!神奇!)

[html]  view plain copy
  1. <html>  
  2. <head>  
  3. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
  4. <title>账户已经冻结</title>  
  5. <style type="text/css">  
  6. <!--  
  7. .temp {  
  8.     font-family: Arial, Helvetica, sans-serif;  
  9.     font-size: 14px;  
  10.     font-weight: bold;  
  11.     color: #666666;  
  12.     margin: 10px;  
  13.     padding: 10px;  
  14.     border: 1px solid #999999;  
  15. }  
  16. .STYLE1 {color: #FF0000}  
  17. -->  
  18. </style>  
  19. </head>  
  20.   
  21. <body>  
  22. <p> </p>  
  23. <p> </p>  
  24. <p> </p>  
  25. <table width="700" border="0" align="center" cellpadding="0" cellspacing="0" class="temp">  
  26.   <tr>  
  27.     <td width="135" height="192"><div align="center"><img src="images/err.jpg" width="54" height="58"></div></td>  
  28.     <td width="563"><p><span class="STYLE1">登录失败</span><br>  
  29.         <br>  
  30.     您的帐户活跃指数低于系统限制,您的帐户已经被暂时冻结。<br>  
  31.     请您联系网络主管或者人事主管重新激活您的帐户。</p>  
  32.     </td>  
  33.   </tr>  
  34. </table>  
  35. <p> </p>  
  36. </body>  
  37. </html>  





一些Web站点用POST形式而不是GET,这是因为POST能够携带更多的数据,而且不用URL,这使得它看起来不那么庞大。使用上面列出的大致的代码,Java代码可以和这些站点轻松的实现对话。 


得到html以后,分析内容就显得相对轻松了。现在就可以使用htmlparser了,下面是一个简单的示例程序,过多的解释我就不说了,相信代码能够说明一切的! 


[java]  view plain copy
  1. package com.test;  
  2.   
  3. import org.htmlparser.Node;  
  4. import org.htmlparser.NodeFilter;  
  5. import org.htmlparser.Parser;  
  6. import org.htmlparser.filters.TagNameFilter;  
  7. import org.htmlparser.tags.TableTag;  
  8. import org.htmlparser.util.NodeList;  
  9.   
  10. /** 
  11. * 标题:利用htmlparser提取网页纯文本的例子 
  12. */  
  13. public class TestHTMLParser {  
  14.   public static void testHtml() {  
  15.     try {  
  16.         String sCurrentLine;  
  17.         String sTotalString;  
  18.         sCurrentLine = "";  
  19.         sTotalString = "";  
  20.         java.io.InputStream l_urlStream;  
  21.         java.net.URL l_url = new java.net.URL("http://www.ideagrace.com/html/doc/2006/07/04/00929.html");  
  22.         java.net.HttpURLConnection l_connection = (java.net.HttpURLConnection) l_url.openConnection();  
  23.         l_connection.connect();  
  24.         l_urlStream = l_connection.getInputStream();  
  25.         java.io.BufferedReader l_reader = new java.io.BufferedReader(new java.io.InputStreamReader(l_urlStream));  
  26.         while ((sCurrentLine = l_reader.readLine()) != null) {  
  27.           sTotalString += sCurrentLine+"/r/n";  
  28.         //  System.out.println(sTotalString);  
  29.         }  
  30.         String testText = extractText(sTotalString);  
  31.         System.out.println( testText );  
  32.   
  33.     } catch (Exception e) {  
  34.         e.printStackTrace();  
  35.     }  
  36.   
  37.   }  
  38.    
  39.   public static String extractText(String inputHtml) throws Exception {  
  40.     StringBuffer text = new StringBuffer();  
  41.     Parser parser = Parser.createParser(new String(inputHtml.getBytes(),"GBK"), "GBK");  
  42.     // 遍历所有的节点  
  43.     NodeList nodes = parser.extractAllNodesThatMatch(new NodeFilter() {  
  44.         public boolean accept(Node node) {  
  45.           return true;  
  46.         }  
  47.     });  
  48.   
  49.     System.out.println(nodes.size()); //打印节点的数量  
  50.     for (int i=0;i<nodes.size();i++){  
  51.          Node nodet = nodes.elementAt(i);  
  52.          //System.out.println(nodet.getText());   
  53.         text.append(new String(nodet.toPlainTextString().getBytes("GBK"))+"/r/n");            
  54.     }  
  55.     return text.toString();  
  56.   }  
  57.    
  58.   public static void test5(String resource) throws Exception {  
  59.     Parser myParser = new Parser(resource);  
  60.     myParser.setEncoding("GBK");  
  61.     String filterStr = "table";  
  62.     NodeFilter filter = new TagNameFilter(filterStr);  
  63.     NodeList nodeList = myParser.extractAllNodesThatMatch(filter);  
  64.     TableTag tabletag = (TableTag) nodeList.elementAt(11);  
  65.        
  66.   }  
  67.   
  68.   public static void main(String[] args) throws Exception {  
  69.     // test5("http://www.ggdig.com");  
  70.     testHtml();  
  71.   }  
  72. }  
配合htmlparser,可以随心所欲的截取别人网站的信息了! 




最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet。post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。 
在Java中可以使用HttpURLConnection发起这两种请求,了解此类,对于了解soap,和编写servlet的自动测试代码都有很大的帮助。 
下面的代码简单描述了如何使用HttpURLConnection发起这两种请求,以及传递参数的方法:

  1. package com.service; 



  2. import java.io.BufferedReader; 

  3. import java.io.DataOutputStream; 

  4. import java.io.IOException; 

  5. import java.io.InputStreamReader; 

  6. import java.net.HttpURLConnection; 

  7. import java.net.URL; 

  8. import java.net.URLEncoder; 



  9. public class HttpInvoker { 



  10.         public static final String GET_URL = " http://localhost:8080/demo/  "; 


  11.         public static final String POST_URL = " http://localhost:8080/demo/  "; 


  12.         public static void readContentFromGet() throws IOException { 

  13.                // 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码 

  14.                String getURL = GET_URL + " ?username= " 

  15.                                + URLEncoder.encode("fat man", " utf-8 "); 

  16.                URL getUrl = new URL(getURL); 

  17.                // 根据拼凑的URL,打开连接,URL.openConnection()函数会根据 URL的类型,返回不同的URLConnection子类的对象,在这里我们的URL是一个http,因此它实际上返回的是HttpURLConnection 

  18.                HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); 

  19.                // 建立与服务器的连接,并未发送数据 

  20.                connection.connect(); 

  21.                // 发送数据到服务器并使用Reader读取返回的数据 

  22.                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

  23.                System.out.println(" ============================= "); 

  24.                System.out.println(" Contents of get request "); 

  25.                System.out.println(" ============================= "); 

  26.                String lines; 

  27.                while ((lines = reader.readLine()) != null) { 

  28.                        System.out.println(lines); 

  29.                } 

  30.                reader.close(); 

  31.                // 断开连接 

  32.                connection.disconnect(); 

  33.                System.out.println(" ============================= "); 

  34.                System.out.println(" Contents of get request ends "); 

  35.                System.out.println(" ============================= "); 

  36.         } 



  37.         public static void readContentFromPost() throws IOException { 

  38.                // Post请求的url,与get不同的是不需要带参数 

  39.                URL postUrl = new URL(POST_URL); 

  40.                // 打开连接 

  41.                HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); 

  42.                //打开读写属性,默认均为false 

  43.                connection.setDoOutput(true);                 

  44.         connection.setDoInput(true); 

  45.                // 设置请求方式,默认为GET 

  46.                connection.setRequestMethod(" POST "); 

  47.                // Post 请求不能使用缓存 

  48.                connection.setUseCaches(false); 

  49.                // URLConnection.setFollowRedirects是static 函数,作用于所有的URLConnection对象。 

  50.                // connection.setFollowRedirects(true); 

  51.                //URLConnection.setInstanceFollowRedirects 是成员函数,仅作用于当前函数 

  52.                connection.setInstanceFollowRedirects(true); 

  53.                // 配置连接的Content-type,配置为application/x- www-form-urlencoded的意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode进行编码 

  54.                connection.setRequestProperty(" Content-Type ", 

  55.                                " application/x-www-form-urlencoded "); 

  56.                // 连接,从postUrl.openConnection()至此的配置必须要在 connect之前完成, 

  57.                // 要注意的是connection.getOutputStream()会隐含的进行调用 connect(),所以这里可以省略 

  58.                //connection.connect(); 

  59.                DataOutputStream out = new DataOutputStream(connection 

  60.                                .getOutputStream()); 

  61.                //正文内容其实跟get的URL中'?'后的参数字符串一致 

  62.                String content = " firstname= "+URLEncoder.encode(" 一个大肥人 ", " utf-8 "); 

  63.                // DataOutputStream.writeBytes将字符串中的16位的 unicode字符以8位的字符形式写道流里面 

  64.                out.writeBytes(content); 

  65.                out.flush(); 

  66.                out.close(); // flush and close 

  67.                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

  68.                String line; 

  69.                System.out.println(" ============================= "); 

  70.                System.out.println(" Contents of post request "); 

  71.                System.out.println(" ============================= "); 

  72.                while ((line = reader.readLine()) != null) { 

  73.                        System.out.println(line); 

  74.                } 

  75.                System.out.println(" ============================= "); 

  76.                System.out.println(" Contents of post request ends "); 

  77.                System.out.println(" ============================= "); 

  78.                reader.close(); 

  79.                //connection.disconnect(); 

  80.         } 



  81.         public static void main(String[] args) { 

  82.                // TODO Auto-generated method stub 

  83.                try { 

  84.                        readContentFromGet(); 

  85.                        readContentFromPost(); 

  86.                } catch (IOException e) { 

  87.                        // TODO Auto-generated catch block 

  88.                        e.printStackTrace(); 

  89.                } 

  90.         } 

  91. }
复制代码
上面的readContentFromGet() 函数产生了一个get请求,传给servlet一个username参数,值为"fat man"。 
readContentFromPost() 函数产生了一个post请求,传给servlet一个firstname参数,值为"一个大肥人"。 
HttpURLConnection.connect函数,实际上只是建立了一个与服务器的 tcp连接,并没有实际发送http请求。无论是post还是get,http请求实际上直到 HttpURLConnection .getInputStream()这个函数里面才正式发送出去。 

在 readContentFromPost() 中,顺序是重中之重,对connection对象的一切配置(那一堆set函数)都必须要在connect()函数执行之前完成。而对 outputStream的写操作,又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。 

http请求实际上由两部分组成,一个是 http头(head),所有关于此次http请求的配置都在http头里面定义,一个是正文(content),在connect()函数里面,会根据 HttpURLConnection对象的配置值生成http头,因此在调用connect函数之前,就必须把所有的配置准备好。 

紧接着http头的是http请求的正文,正文的内容通过outputStream写入,实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,而是在流关闭后,根据输入的内容生成http正文。 

至此,http请求的东西已经准备就绪。在 getInputStream()函数调用的时候,就会把准备好的http请求正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http 请求的返回信息。由于http请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在 getInputStream()函数之后对connection对象进行设置(对http头的信息进行修改)或者写入outputStream(对正文进行修改)都是没有意义的了,甚至执行这些操作可能会导致异常的发生


JDK 中提供了一些对无状态协议请求(HTTP )的支持,下面我就将我所写的一个小例子(组件)进行描述:

 首先让我们先构建一个请求类(HttpRequester )。

该类封装了 JAVA 实现简单请求的代码,如下:

Java代码   收藏代码
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.InputStreamReader;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7. import java.nio.charset.Charset;  
  8. import java.util.Map;  
  9. import java.util.Vector;  
  10.    
  11. /** 
  12.  * HTTP请求对象 
  13.  *  
  14.  * @author YYmmiinngg 
  15.  */  
  16. public class HttpRequester {  
  17.     private String defaultContentEncoding;  
  18.    
  19.     public HttpRequester() {  
  20.         this.defaultContentEncoding = Charset.defaultCharset().name();  
  21.     }  
  22.    
  23.     /** 
  24.      * 发送GET请求 
  25.      *  
  26.      * @param urlString 
  27.      *            URL地址 
  28.      * @return 响应对象 
  29.      * @throws IOException 
  30.      */  
  31.     public HttpRespons sendGet(String urlString) throws IOException {  
  32.         return this.send(urlString, "GET"nullnull);  
  33.     }  
  34.    
  35.     /** 
  36.      * 发送GET请求 
  37.      *  
  38.      * @param urlString 
  39.      *            URL地址 
  40.      * @param params 
  41.      *            参数集合 
  42.      * @return 响应对象 
  43.      * @throws IOException 
  44.      */  
  45.     public HttpRespons sendGet(String urlString, Map<String, String> params)  
  46.             throws IOException {  
  47.         return this.send(urlString, "GET", params, null);  
  48.     }  
  49.    
  50.     /** 
  51.      * 发送GET请求 
  52.      *  
  53.      * @param urlString 
  54.      *            URL地址 
  55.      * @param params 
  56.      *            参数集合 
  57.      * @param propertys 
  58.      *            请求属性 
  59.      * @return 响应对象 
  60.      * @throws IOException 
  61.      */  
  62.     public HttpRespons sendGet(String urlString, Map<String, String> params,  
  63.             Map<String, String> propertys) throws IOException {  
  64.         return this.send(urlString, "GET", params, propertys);  
  65.     }  
  66.    
  67.     /** 
  68.      * 发送POST请求 
  69.      *  
  70.      * @param urlString 
  71.      *            URL地址 
  72.      * @return 响应对象 
  73.      * @throws IOException 
  74.      */  
  75.     public HttpRespons sendPost(String urlString) throws IOException {  
  76.         return this.send(urlString, "POST"nullnull);  
  77.     }  
  78.    
  79.     /** 
  80.      * 发送POST请求 
  81.      *  
  82.      * @param urlString 
  83.      *            URL地址 
  84.      * @param params 
  85.      *            参数集合 
  86.      * @return 响应对象 
  87.      * @throws IOException 
  88.      */  
  89.     public HttpRespons sendPost(String urlString, Map<String, String> params)  
  90.             throws IOException {  
  91.         return this.send(urlString, "POST", params, null);  
  92.     }  
  93.    
  94.     /** 
  95.      * 发送POST请求 
  96.      *  
  97.      * @param urlString 
  98.      *            URL地址 
  99.      * @param params 
  100.      *            参数集合 
  101.      * @param propertys 
  102.      *            请求属性 
  103.      * @return 响应对象 
  104.      * @throws IOException 
  105.      */  
  106.     public HttpRespons sendPost(String urlString, Map<String, String> params,  
  107.             Map<String, String> propertys) throws IOException {  
  108.         return this.send(urlString, "POST", params, propertys);  
  109.     }  
  110.    
  111.     /** 
  112.      * 发送HTTP请求 
  113.      *  
  114.      * @param urlString 
  115.      * @return 响映对象 
  116.      * @throws IOException 
  117.      */  
  118.     private HttpRespons send(String urlString, String method,  
  119.             Map<String, String> parameters, Map<String, String> propertys)  
  120.             throws IOException {  
  121.         HttpURLConnection urlConnection = null;  
  122.    
  123.         if (method.equalsIgnoreCase("GET") && parameters != null) {  
  124.             StringBuffer param = new StringBuffer();  
  125.             int i = 0;  
  126.             for (String key : parameters.keySet()) {  
  127.                 if (i == 0)  
  128.                     param.append("?");  
  129.                 else  
  130.                     param.append("&");  
  131.                 param.append(key).append("=").append(parameters.get(key));  
  132.                 i++;  
  133.             }  
  134.             urlString += param;  
  135.         }  
  136.         URL url = new URL(urlString);  
  137.         urlConnection = (HttpURLConnection) url.openConnection();  
  138.    
  139.         urlConnection.setRequestMethod(method);  
  140.         urlConnection.setDoOutput(true);  
  141.         urlConnection.setDoInput(true);  
  142.         urlConnection.setUseCaches(false);  
  143.    
  144.         if (propertys != null)  
  145.             for (String key : propertys.keySet()) {  
  146.                 urlConnection.addRequestProperty(key, propertys.get(key));  
  147.             }  
  148.    
  149.         if (method.equalsIgnoreCase("POST") && parameters != null) {  
  150.             StringBuffer param = new StringBuffer();  
  151.             for (String key : parameters.keySet()) {  
  152.                 param.append("&");  
  153.                 param.append(key).append("=").append(parameters.get(key));  
  154.             }  
  155.             urlConnection.getOutputStream().write(param.toString().getBytes());  
  156.             urlConnection.getOutputStream().flush();  
  157.             urlConnection.getOutputStream().close();  
  158.         }  
  159.    
  160.         return this.makeContent(urlString, urlConnection);  
  161.     }  
  162.    
  163.     /** 
  164.      * 得到响应对象 
  165.      *  
  166.      * @param urlConnection 
  167.      * @return 响应对象 
  168.      * @throws IOException 
  169.      */  
  170.     private HttpRespons makeContent(String urlString,  
  171.             HttpURLConnection urlConnection) throws IOException {  
  172.         HttpRespons httpResponser = new HttpRespons();  
  173.         try {  
  174.             InputStream in = urlConnection.getInputStream();  
  175.             BufferedReader bufferedReader = new BufferedReader(  
  176.                     new InputStreamReader(in));  
  177.             httpResponser.contentCollection = new Vector<String>();  
  178.             StringBuffer temp = new StringBuffer();  
  179.             String line = bufferedReader.readLine();  
  180.             while (line != null) {  
  181.                 httpResponser.contentCollection.add(line);  
  182.                 temp.append(line).append("\r\n");  
  183.                 line = bufferedReader.readLine();  
  184.             }  
  185.             bufferedReader.close();  
  186.    
  187.             String ecod = urlConnection.getContentEncoding();  
  188.             if (ecod == null)  
  189.                 ecod = this.defaultContentEncoding;  
  190.    
  191.             httpResponser.urlString = urlString;  
  192.    
  193.             httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();  
  194.             httpResponser.file = urlConnection.getURL().getFile();  
  195.             httpResponser.host = urlConnection.getURL().getHost();  
  196.             httpResponser.path = urlConnection.getURL().getPath();  
  197.             httpResponser.port = urlConnection.getURL().getPort();  
  198.             httpResponser.protocol = urlConnection.getURL().getProtocol();  
  199.             httpResponser.query = urlConnection.getURL().getQuery();  
  200.             httpResponser.ref = urlConnection.getURL().getRef();  
  201.             httpResponser.userInfo = urlConnection.getURL().getUserInfo();  
  202.    
  203.             httpResponser.content = new String(temp.toString().getBytes(), ecod);  
  204.             httpResponser.contentEncoding = ecod;  
  205.             httpResponser.code = urlConnection.getResponseCode();  
  206.             httpResponser.message = urlConnection.getResponseMessage();  
  207.             httpResponser.contentType = urlConnection.getContentType();  
  208.             httpResponser.method = urlConnection.getRequestMethod();  
  209.             httpResponser.connectTimeout = urlConnection.getConnectTimeout();  
  210.             httpResponser.readTimeout = urlConnection.getReadTimeout();  
  211.    
  212.             return httpResponser;  
  213.         } catch (IOException e) {  
  214.             throw e;  
  215.         } finally {  
  216.             if (urlConnection != null)  
  217.                 urlConnection.disconnect();  
  218.         }  
  219.     }  
  220.    
  221.     /** 
  222.      * 默认的响应字符集 
  223.      */  
  224.     public String getDefaultContentEncoding() {  
  225.         return this.defaultContentEncoding;  
  226.     }  
  227.    
  228.     /** 
  229.      * 设置默认的响应字符集 
  230.      */  
  231.     public void setDefaultContentEncoding(String defaultContentEncoding) {  
  232.         this.defaultContentEncoding = defaultContentEncoding;  
  233.     }  
  234. }  

 

 

其次我们来看看响应对象(HttpRespons )。 响应对象其实只是一个数据BEAN ,由此来封装请求响应的结果数据,如下:
Java代码   收藏代码
  1. import java.util.Vector;  
  2.    
  3. /** 
  4.  * 响应对象 
  5.  */  
  6. public class HttpRespons {  
  7.    
  8.     String urlString;  
  9.    
  10.     int defaultPort;  
  11.    
  12.     String file;  
  13.    
  14.     String host;  
  15.    
  16.     String path;  
  17.    
  18.     int port;  
  19.    
  20.     String protocol;  
  21.    
  22.     String query;  
  23.    
  24.     String ref;  
  25.    
  26.     String userInfo;  
  27.    
  28.     String contentEncoding;  
  29.    
  30.     String content;  
  31.    
  32.     String contentType;  
  33.    
  34.     int code;  
  35.    
  36.     String message;  
  37.    
  38.     String method;  
  39.    
  40.     int connectTimeout;  
  41.    
  42.     int readTimeout;  
  43.    
  44.     Vector<String> contentCollection;  
  45.    
  46.     public String getContent() {  
  47.         return content;  
  48.     }  
  49.    
  50.     public String getContentType() {  
  51.         return contentType;  
  52.     }  
  53.    
  54.     public int getCode() {  
  55.         return code;  
  56.     }  
  57.    
  58.     public String getMessage() {  
  59.         return message;  
  60.     }  
  61.    
  62.     public Vector<String> getContentCollection() {  
  63.         return contentCollection;  
  64.     }  
  65.    
  66.     public String getContentEncoding() {  
  67.         return contentEncoding;  
  68.     }  
  69.    
  70.     public String getMethod() {  
  71.         return method;  
  72.     }  
  73.    
  74.     public int getConnectTimeout() {  
  75.         return connectTimeout;  
  76.     }  
  77.    
  78.     public int getReadTimeout() {  
  79.         return readTimeout;  
  80.     }  
  81.    
  82.     public String getUrlString() {  
  83.         return urlString;  
  84.     }  
  85.    
  86.     public int getDefaultPort() {  
  87.         return defaultPort;  
  88.     }  
  89.    
  90.     public String getFile() {  
  91.         return file;  
  92.     }  
  93.    
  94.     public String getHost() {  
  95.         return host;  
  96.     }  
  97.    
  98.     public String getPath() {  
  99.         return path;  
  100.     }  
  101.    
  102.     public int getPort() {  
  103.         return port;  
  104.     }  
  105.    
  106.     public String getProtocol() {  
  107.         return protocol;  
  108.     }  
  109.    
  110.     public String getQuery() {  
  111.         return query;  
  112.     }  
  113.    
  114.     public String getRef() {  
  115.         return ref;  
  116.     }  
  117.    
  118.     public String getUserInfo() {  
  119.         return userInfo;  
  120.     }  
  121.    
  122. }  

 

 

最后,让我们写一个应用类,测试以上代码是否正确

Java代码   收藏代码
  1. import com.yao.http.HttpRequester;  
  2. import com.yao.http.HttpRespons;  
  3.    
  4. public class Test {  
  5.     public static void main(String[] args) {  
  6.         try {  
  7.             HttpRequester request = new HttpRequester();  
  8.             HttpRespons hr = request.sendGet("http://www.csdn.net");  
  9.    
  10.             System.out.println(hr.getUrlString());  
  11.             System.out.println(hr.getProtocol());  
  12.             System.out.println(hr.getHost());  
  13.             System.out.println(hr.getPort());  
  14.             System.out.println(hr.getContentEncoding());  
  15.             System.out.println(hr.getMethod());  
  16.               
  17.             System.out.println(hr.getContent());  
  18.    
  19.         } catch (Exception e) {  
  20.             e.printStackTrace();  
  21.         }  
  22.     }  
  23. }  
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值