http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 194575|回复: 2

[Java] Java版【HttpHelper】没有飞哥的强大只是实现功能,给个位一个启发把

[复制链接]
发表于 2014-1-29 13:05:47 | 显示全部楼层 |阅读模式

本身自己是学Java的但是平时自己在家里不知道写点什么,用Java去窗口扯淡了,自己去写个网页没创意而且网页麻烦美化什么的等等问题,所以平时一直在用C#写窗口用Java的时间越来越少,学的知识全丢给老师还了!自从看到飞哥的HttpHelper类之后就有点心动按照飞哥的思路写一个Java的HttpHelper类所以现在写了一个简约的,给大家玩玩!接下去我会好好按照飞哥的思路写的更加完善!


代码如下:

[Java] 纯文本查看 复制代码
package com.ebbbe.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;



/**
 * HttpHelper
 * @author Lese
 * 
 * @version 1.0。0。0
 * 
 */
public class HttpHelper {
    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param item
     *            发送请求的 参数
     * [url=home.php?mod=space&uid=3039]@return[/url] URL 所代表远程资源的响应结果
     */
    public static String sendGet(HttpItem item) {
        String result = "";
        BufferedReader in = null;
        try {
        	String urlNameString ="";
        	if(item.getURL().contains("http://")){
        		urlNameString = item.getURL();
        	}else{
        		
        		urlNameString = "http://"+item.getURL();
        	}
            
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", item.getAccept());
            connection.setRequestProperty("connection", item.getConnection());
            connection.setRequestProperty("user-agent",item.getUserAgent());
            connection.setRequestProperty("Referer",item.getReferer());
            connection.setRequestProperty("Cookie",item.getCookie());
            connection.setRequestProperty("Host",item.getHost());
            connection.setRequestProperty("Content-Type", item.getContentType());
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println("\n\n"+key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param item
     *            发送请求的 参数
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(HttpItem item) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
        	String urlNameString ="";
        	if(item.getURL().contains("http://")){
        		urlNameString = item.getURL();
        	}else{
        		
        		urlNameString = "http://"+item.getURL();
        	}
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", item.getAccept());
            conn.setRequestProperty("connection", item.getConnection());
            conn.setRequestProperty("user-agent",item.getUserAgent());
            conn.setRequestProperty("Referer",item.getReferer());
            conn.setRequestProperty("Cookie",item.getCookie());
            conn.setRequestProperty("Host",item.getHost());
            conn.setRequestProperty("Content-Type", item.getContentType());
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(item.getPstData());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
}

class HttpItem{
	//访问网址
	String URL;
	//设置Host的标头信息
	String host;
	//请求标头值 默认为text/html, application/xhtml+xml, */*
	String accept="text/html, application/xhtml+xml, */*";
	//请求返回类型默认 text/html
	String contentType="text/html";
	//客户端访问信息默认Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
	String userAgent="Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
	//Post数据
	String pstData="";
	// 来源地址,上次访问地址
	String referer="";
	//Cookie
	String cookie="";
	//
	String connection="Keep-Alive";

	public String getHost() {
		return host;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public String getAccept() {
		return accept;
	}
	public void setAccept(String accept) {
		this.accept = accept;
	}
	public String getContentType() {
		return contentType;
	}
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	public String getUserAgent() {
		return userAgent;
	}
	public void setUserAgent(String userAgent) {
		this.userAgent = userAgent;
	}
	public String getPstData() {
		return pstData;
	}
	public void setPstData(String pstData) {
		this.pstData = pstData;
	}
	public String getReferer() {
		return referer;
	}
	public void setReferer(String referer) {
		this.referer = referer;
	}
	public String getCookie() {
		return cookie;
	}
	public void setCookie(String cookie) {
		this.cookie = cookie;
	}
	public String getConnection() {
		return connection;
	}
	public void setConnection(String connection) {
		this.connection = connection;
	}
	public String getURL() {
		return URL;
	}
	public void setURL(String uRL) {
		URL = uRL;
	}
}


使用方法当然是和飞哥的差不多:

[Java] 纯文本查看 复制代码
package com.ebbbe.http;

public class test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		HttpItem item=new HttpItem();
		item.setURL("www.baidu.com");
		System.out.print("\n\n"+HttpHelper.sendGet(item));
		
	}

}



1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
发表于 2014-1-29 14:08:42 | 显示全部楼层
可以再完善下,我过年放假,等回来细说,七号上班
发表于 2017-1-23 22:28:46 | 显示全部楼层
支持!原创就好。
其实不在于有多少花里胡哨的技巧,只要是有实用价值就好。
新手支持!感谢分享!!!
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-4-24 20:05

© 2014-2021

快速回复 返回顶部 返回列表