2012-04-02 15 views
12

私はjavaでURLを開く機会を探しています。JavaでURLを開いてコンテンツを取得する

URL url = new URL("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de"); 
    InputStream is = url.openConnection().getInputStream(); 

    BufferedReader reader = new BufferedReader(new InputStreamReader(is) ); 

    String line = null; 
    while((line = reader.readLine()) != null) { 
     System.out.println(line); 
    } 
    reader.close(); 

私はその方法を見つけました。

自分のプログラムに追加しました。次のエラーが発生しました。

The method openConnection() is undefined for the type URL 

(url.openConnectionによって())

私の問題は何ですか?

私は、サーブレットとTomcatのサーバを使用し、...

+0

これを試してみてください:http://docs.oracle.com/javase/tutor ial/networking/urls/readingURL.html – shem

+0

問題は、 'java.net.URL'を使わず、' URL'と呼ばれる他のクラスを使用している可能性が高い*でしょう。 –

+1

ありがとう....それは動作します;) –

答えて

2

あなたはjava.net.URLクラスを使用してよろしいですか?インポートステートメントを確認してください。

5

私のために働く。 正しい輸入品を使用しているかどうか確認してください。

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.URL; 
1

HTTPを扱うときには、アクセス拒否のようなより多くのものがありますthis

などのようなHTTPクライアントライブラリを使用することがより有用である可能性がある、ドキュメントが処理するためなどに移動しました。

はあなただけでWebページを開きたい場合は

13
public class UrlContent{ 
    public static void main(String[] args) { 

     URL url; 

     try { 
      // get URL content 

      String a="http://localhost:8080/TestWeb/index.jsp"; 
      url = new URL(a); 
      URLConnection conn = url.openConnection(); 

      // open the stream and put it into BufferedReader 
      BufferedReader br = new BufferedReader(
           new InputStreamReader(conn.getInputStream())); 

      String inputLine; 
      while ((inputLine = br.readLine()) != null) { 
        System.out.println(inputLine); 
      } 
      br.close(); 

      System.out.println("Done"); 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 
} 
8
String url_open ="http://javadl.sun.com/webapps/download/AutoDL?BundleId=76860"; 
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url_open)); 
4

コードは動作するはずです後、

URL url = new URL("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de"); 
InputStream is = url.openConnection().getInputStream(); 

BufferedReader reader = new BufferedReader(new InputStreamReader(is) ); 

String line = null; 
while((line = reader.readLine()) != null) { 
    System.out.println(line); 
} 
reader.close(); 
1

、私は以下であると思います(ただし、この場合はほとんどありません)この場合の詳細:

import java.awt.Desktop; 
import java.net.URI; //Note this is URI, not URL 

class BrowseURL{ 
    public static void main(String args[]) throws Exception{ 
     // Create Desktop object 
     Desktop d=Desktop.getDesktop(); 

     // Browse a URL, say google.com 
     d.browse(new URI("http://google.com")); 

     } 
    } 
}