2010-12-01 62 views
2

晚上好大家
我想在Java中使用Socket类来获取一个网页,我已经做到了这一点作为使用Java Socket类

import java.net.*; 
import java.io.*; 

class htmlPageFetch{ 
     public static void main(String[] args){ 
       try{ 
         Socket s = new Socket("127.0.0.1", 80); 
         DataInputStream dIn = new DataInputStream(s.getInputStream()); 
         DataOutputStream dOut = new DataOutputStream(s.getOutputStream()); 
         dOut.write("GET /index.php HTTP/1.0\n\n".getBytes()); 
         boolean more_data = true; 
         String str; 
         while(more_data){ 
           str = dIn.readLine(); 
if(str==null) 
more_data = false; 
           System.out.println(str); 
         } 
       }catch(IOException e){ 

       } 
     } 
} 

获取一个网页,但它只是给空的。

输出

HTTP/1.1 302 Found 
Date: Wed, 01 Dec 2010 13:49:02 GMT 
Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8k PHP/5.2.9 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 
X-Powered-By: PHP/5.2.9 
Location: http://localhost/xampp/ 
Content-Length: 0 
Content-Type: text/html 

null 

回答

2

我不知道这是否是引起您的问题,但HTTP预计,换行回车和换行:

dOut.write("GET /index.php HTTP/1.0\r\n\r\n".getBytes()); 

而且,它不会伤害冲洗并关闭DataOutputStream类:

dOut.flush(); 
dOut.close(); 

如果你打算使用此代码不仅仅是连接到简单的测试案例更做任何事情,我会使用,而不是在一个插座自己implenting HTTP HttpURLConnection的这个建议。否则,结果将不仅仅包含网页。它还将包含HTTP响应,包括状态码和标题。你的代码需要解析。

更新:

看着你添加的响应,与位置沿302响应:头表示你正在寻找的页面搬到http://localhost/xampp/(见HTTP 302),并不再有任何内容在原始网址。这可以设置为由HttpURLConnection或其他库如Apache HttpClient自动处理。您需要解析状态码,解析标题,打开一个新的套接字到响应位置并获取页面。根据您的任务的确切要求,您可能还需要熟悉HTTP 1.0 SpecificationHTTP 1.1 Specification

+0

雅拉兹这是真的,但我想这样做使用套接字,因为它是我的任务分析收到的输出 – codeomnitrix 2010-12-01 13:59:28

1

我想代码工作,也许除了你没有看到输出,因为它是由所有的null是你打印淹没。你应该在第一个null之后停下来。 更一般地说,DataInputStreamDataOutputStream不适合这份工作。试试这个代码。

public static void main(String[] args) throws IOException { 
    Socket s = new Socket("127.0.0.1", 80); 
    BufferedReader dIn = new BufferedReader(new InputStreamReader(s.getInputStream())); 
    PrintStream dOut = new PrintStream(s.getOutputStream()); 
    dOut.println("GET /index.php HTTP/1.0"); 
    dOut.println(); 
    String str = null; 
    do { 
     str = dIn.readLine(); 
     System.out.println(str); 
    } while (str != null); 
} 
+0

嘿弗拉维奥雅正在工作,但我无法看到整个页面的内容。只有“标题”显示给我,然后“空”我已经将输出添加到问题。请检查这个 – codeomnitrix 2010-12-01 13:51:34

0

为什么直接使用套接字来执行HTTP连接?这是很好的练习,但它需要深入了解HTTP协议的内部知识。为什么不只是使用类URL和URLConnection?

BufferedReader dIn = new BufferedReader(new URL("http://127.0.0.1:80").openConnection().getInputStream()); 
do { 
     str = dIn.readLine(); 
     System.out.println(str); 
    } while (str != null); 
} 
+0

嘿,这很好,但我想用插座,因为它是我的任务 – codeomnitrix 2010-12-01 14:00:16