苏飞论坛

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

作者: Lese    时间: 2014-1-29 13:05
标题: Java版【HttpHelper】没有飞哥的强大只是实现功能,给个位一个启发把

本身自己是学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
     *            发送请求的 参数
     * @return 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));
               
        }

}


作者: 站长苏飞    时间: 2014-1-29 14:08
可以再完善下,我过年放假,等回来细说,七号上班
作者: cload    时间: 2017-1-23 22:28
支持!原创就好。
其实不在于有多少花里胡哨的技巧,只要是有实用价值就好。
新手支持!感谢分享!!!




欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4