java 傳送http請求 返回字串 再進行解析(略)
阿新 • • 發佈:2018-12-31
package taobao.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.util.Map; import java.util.Set; /** * * @author Administrator * */ public class postUrlgetJson { public static String getDataFromURL(String strURL, Map<String, Object> param) throws Exception { URL url = new URL(strURL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); final StringBuilder sb; if (param != null) { sb = new StringBuilder(param.size() << 4);// 4次方 final Set<String> keys = param.keySet(); for (final String key : keys) { final Object value = param.get(key); sb.append(key); // 不能包含特殊字元 sb.append('='); sb.append(value); sb.append('&'); } // 將最後的 '&' 去掉 sb.deleteCharAt(sb.length() - 1); }else{ sb = new StringBuilder(100 << 4); } writer.write(sb.toString()); writer.flush(); writer.close(); InputStreamReader reder = new InputStreamReader(conn.getInputStream(), "utf-8"); BufferedReader breader = new BufferedReader(reder); BufferedWriter w = new BufferedWriter(new FileWriter("d:/1.txt"));//獲取內容輸出到指定檔案 String content = null; String result = null; while ((content = breader.readLine()) != null) { result += content; } w.write(result); w.flush(); w.close(); return result; } //main方法 public static void main(String[] args) { String strURL = "http://open.taobao.com/index.htm"; try { //呼叫傳送請求方法 String result = getDataFromURL(strURL, null); //輸出url返回內容 如上面的htm頁面的原始檔 返回結果 System.out.println("result:"+result); } catch (Exception e) { e.printStackTrace(); } } }