サンプル
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) { try { System.out.println("-= Get -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); System.out.println(getContent("http://www.alc.co.jp/", false)); System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); System.out.println("-= Post -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); System.out.println(getContent("http://www.msn.com/ja-jp", true)); System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); } catch (IOException ex) { ex.printStackTrace(); } } /** * コンテンツ取得 * @param targetUrl URL * @param isPost POST通信か * @return コンテンツ * @throws IOException */ private static String getContent(String targetUrl, boolean isPost) throws IOException { URL url = new URL(targetUrl); HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Accept-Language", "ja"); if (isPost) { connection.setDoOutput(true); connection.setRequestMethod("POST"); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8)); writer.write(System.getProperty("line.separator")); writer.flush(); } else { connection.setRequestMethod("GET"); } if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { System.out.println("Error : " + connection.getResponseCode()); return null; } try ( InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { StringBuilder returnValue = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { returnValue.append(line); //returnValue.append(System.getProperty("line.separator")); } return returnValue.toString(); } } finally { if (connection != null) { connection.disconnect(); } } } }
出力結果
-= Get -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w ・・・略・・・ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -= Post -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= <?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE HTML PUBLIC "-//WAPFORU ・・・略・・・ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=