URL 网上抓数据

    今天,终于明白了别人是怎么在网上抓数据的.
package com.roadway.phserver.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**//**
 * <p>
 * 本类用于Post一个URL,并返回它的内容
 * <p>
 * 
 * @author huiwanpeng
 * @time 2008-1-24
 * @see no
 
*/

public class SendPost {
    
/**//** url */
    private URL url;

    
/**//** url连接 */
    private URLConnection conn;

    
public SendPost() {
    }

    
/**//**
     * <p>
     * 本方法根据一个字符串创建一个URL,并打开URL的连接
     * <p>
     * 
     * @param urlAddr
     *            URL地址
     
*/

    
public void setURL(String urlAddr) {
        try {
            
/**//** 创建一个URL */
            url 
= new URL(urlAddr);
            
/**//** 打开URL连接 */
            conn 
= url.openConnection();
        } catch (MalformedURLException ex) {
            
/**//** 错误URL产生异常 */
            ex.printStackTrace();
        } catch (IOException ex) {
            
/**//** 输入输出异常 */
            ex.printStackTrace();
        }
    }

    
/**//**
     * <p>
     * 本方法用于POST一个消息
     * <p>
     * 
     * @param post
     *            要POST的参数,比如user=huiwanpeng&password=hwp##
     
*/

    
public void sendPost(String post) {
        
/**//** 打算将URL连接进行输入 */
        conn.setDoInput(true);
        
/**//** 打算将URL连接进行输出 */
        conn.setDoOutput(true);
        
/**//** 声明的一个打印输出流 */
        PrintWriter pw 
= null;
        try {
            pw 
= new PrintWriter(conn.getOutputStream());
            pw.
print(post);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.
close();
        }
    }

    
public String getContent() {
        
/**//** 某一行的内容 */
        String line 
= null;
        
/**//** 最终内容 */
        String result 
= "";
        try {
            
/**//** 打开到此 URL 引用的资源的通信链接 */
            conn.connect();
            BufferedReader br 
= new BufferedReader(new InputStreamReader(conn
                    .getInputStream()));
            
/**//** 一行一行地读,直到读完 */
            
while ((line = br.readLine()) != null) {
                result 
+= line + "\n";
            }
            
/**//** 关闭连接 */
            br.
close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
return result;
    }

    
public static void main(String[] args) {
        String urlAddr 
= "http://www.ip138.com:8080/search.asp";
        String post 
= "action=mobile&mobile=13501678250";
        SendPost test 
= new SendPost();
        test.setURL(urlAddr);
        test.sendPost(post);
        String aa 
= test.getContent().trim();
        System.out.println(aa);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值