java-讀取txt檔案中的第一行URL並進行請求,得出響應
阿新 • • 發佈:2018-12-20
背景:其實我是拿來練手的。想寫程式碼而已,並沒有啥特殊的目地
我的需求:
有一個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)); } } }
不懂的留言呼叫,提供解答,這寫部落格真不知道如何拆開來分析。