背景:其实我是拿来练手的。想写代码而已,并没有啥特殊的目地
我的需求:
有一个url.txt文件,里面装的一行一行的URL
我要请求每一行URL,然后去请求,拿到第一个请求的响应结果,代码很简单,网上一搜遍地都是,我加工了一下。 整合了
直接上码吧!
package snippet;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class GetUrlReqInfo {
/**
* 请求的url链接 返回的是json字符串
* @param urlStr
* @return
* @throws MalformedURLException
*/
public static List<String> txt2String(String txt){
File file = new File(txt);
//StringBuilder result = new StringBuilder();
List<String> urList=new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
// result.append(System.lineSeparator()+s);
urList.add(s);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return urList;
}
public static HashMap<String, String> getURLContent(String txt) throws MalformedURLException {
//ReadFiledata rfd=new ReadFiledata();
List<String> urlList=txt2String(txt);
int i=0;
Map<String, String> haha=new HashMap<String, String>();
for (String string : urlList) {
i++;
//请求的url
System.out.println("取到的URL=="+string);
URL url = new URL(string);
//请求的输入流
BufferedReader in = null;
//输入流的缓冲
StringBuffer sb = new StringBuffer();
String str = null;
try{
in = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8") );
//一行一行进行读入
while((str = in.readLine()) != null) {
sb.append( str );
}
} catch (Exception ex) {
} finally{
try{
if(in!=null) {
in.close(); //关闭流
}
}catch(IOException ex) {
}
System.out.println("取第"+i+"个URL==="+string);
System.out.println("取第"+i+"个URL==="+string+"请求的结果是:==="+sb.toString());
haha.put(string, sb.toString());
}
}
return (HashMap<String, String>) haha;
}
public static void main(String[] args) throws MalformedURLException {
Map<String, String> haha=getURLContent("E:\\项目\\2018年\\11月份\\url.txt");
for(String key:haha.keySet())
{
System.out.println("Key: "+key+" Value: "+haha.get(key));
}
}
}
不懂的留言呼叫,提供解答,这写博客真不知道如何拆开来分析。
版权声明:本文为sincool1003原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。