{{category プログラミング}} {{category Java}} !GETメソッド HTTPコネクションをはって,データを取得する. import java.net.URL; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.io.*; public class HttpGetTest { public HttpURLConnection connection; private String newline = System.getProperty("line.separator"); public HttpGetTest(String url){ try{ URL u = new URL(url); connection = (HttpURLConnection)u.openConnection(); connection.setRequestMethod("GET"); HttpURLConnection.setFollowRedirects(false); connection.setInstanceFollowRedirects(false); }catch(MalformedURLException e){ e.printStackTrace(); } catch (ProtocolException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 接続し,ウェブサイトからのレスポンスを読み込む */ public void read(OutputStream out){ try { connection.connect(); } catch (IOException e) { e.printStackTrace(); } try { byte[] buf = new byte[1024]; int length = connection.getContentLength(); DataInputStream in = new DataInputStream(connection.getInputStream()); int len = 0; int sum = 0; System.out.println("length: " + length); System.out.print(" *"); while((len = in.read(buf)) > 0){ sum += len; if(sum > length/10){ System.out.print("*"); sum = 0; } out.write(buf, 0, len); } } catch (IOException e) { e.printStackTrace(); } connection.disconnect(); } public static void main(String[] args) throws Exception{ HttpGetTest http = new HttpGetTest(args[0]); StringWriter out = new StringWriter(); String path = http.connection.getURL().getFile(); int index = path.lastIndexOf('/'); String file = path.substring(index+1); if(file.equals("")) file = "default.out"; System.out.println("output => " + file); System.out.print(" "); http.read(new FileOutputStream(file)); System.out.println(); //System.out.println(http.connection.getContentType()); //System.out.println(http.connection.getContentEncoding()); //System.out.println(out); } }