使用原生的java类进行URL解析

使用原生的java类进行URL解析

在解析json请求中用到了使用java的原生类去解析一个URL,再通过对回传的json数据进行解析,越过了使用ajax在前台异步请求时遇到的跨域问题

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

/**
 * Created by zwl on 2017/9/15.
 * May god bless me
 */
public class Main {
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url ;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HtmlParse,解析给定url中的中文字符,输出到文本文件中: url:可配置多个 输出路径:可配置 package com.lhs; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 现在要求用Java编写一个程序,该程序访问上面的URL,并从页面中, * 提取出上图所示位置的页面信息(仅图中所要求的内容),将其内容按如下格式,输出到控制台 * GrapWeatherInfo * @author lihsh * @version 1.0 * */ public class HtmlParse { List configList = new ArrayList(); private String savePath = "d:\\htmlParse.txt"; private String reg = "[\u4E00-\u9FA5]+"; Set resultSet = new LinkedHashSet(); /** * @param args */ public static void main(String[] args) { HtmlParse hp = new HtmlParse(); hp.getConfig(); hp.start(); hp.write2file(); } /** * 获得配置文件,得到公司要求的文件型 */ private void getConfig() { Properties props = new Properties(); InputStream in = getClass().getResourceAsStream("/config.properties"); try { props.load(in); Enumeration en = props.propertyNames(); System.out.print("读取配置文件:"); while(en.hasMoreElements()) { String key = (String) en.nextElement(); String value = (String) props.get(key); if(key.startsWith("url")) { configList.add(value); }else if(key.equals("savePath")) { savePath = value; }else if(key.equals("reg")) { reg = value; } System.out.print(key + ":" + value +"; "); } System.out.println(); } catch (IOException e) { e.printStackTrace(); System.out.println("读取配置文件/config.properties出错"); } } /** * 程序总入口 */ private void start() { for(int i = 0; i < configList.size(); i++) { URLConnection con = getConnection(configList.get(i)); readContent(con); System.out.println("读取:" + configList.get(i) + " 结束"); } } /** * 获取url链接 * @return 链接 */ private URLConnection getConnection(String _url) { URLConnection con = null; URL url = null; try { url = new URL(_url); con=url.openConnection(); } catch (IOException e) { e.printStackTrace(); } return con; } /** * 初步过滤出含有天气的行 * @param con url链接 * @return 关键行 */ private void readContent(URLConnection con) { BufferedReader br=null; BufferedWriter bw = null; try { br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8")); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(savePath)), "UTF-8")); String line=""; while((line=br.readLine()) != null) { resultSet.addAll(parse(line)); } bw.flush(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); }finally { try { bw.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 正则表达式匹配关键数据 * @param line * @return */ private Set parse(String line) { Set resSet = new LinkedHashSet(); Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(line); while(matcher.find()) { String group = matcher.group(); resSet.add(group); } return resSet; } private void write2file() { BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(savePath)), "UTF-8")); for(Iterator it = resultSet.iterator(); it.hasNext();) { bw.write(it.next()); bw.newLine(); } bw.flush(); System.out.println("解析结果保存至:" + savePath); } catch (IOException e1) { e1.printStackTrace(); }finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值