2012-10-11 60 views
0

我正在搜索一些关于发送HTTP请求的示例,以便通过使用java在浏览器上显示网页。我找不到一个简单的例子。你有什么建议吗 ?我应该在哪里寻找一个有解释的好例子?谢谢显示带有HTTP请求的网页

+3

你的问题不明确。你的意思是你想创建运行在客户端的Java应用程序,打开用户的默认浏览器并在其中显示网页? – AlexR

+0

现在是的,我只想查看http请求的基本知识以及如何通过发送http请求在浏览器上显示网页。正如你所说这是一个Java应用程序,并在客户端运行。 –

回答

0

使用

Desktop.browse("http://stackoverflow.com/questions/12844363/displaying-a-web-page-with-http-request"); 

此外

+0

'java.awt'包永远不会让我感到惊讶。 (http://stackoverflow.com/q/58305/1374678) – rolve

1

请参见您可以在第j使用 java.net.URL, java.net.URLConnection, java.io.InputStream, org.apache.commons.io.IOUtils管理HTTP请求AVA应用

下面是一个例子类 -

public class HttpUtil 
{ 
    static URL url; 
    static URLConnection urlConn; 
    static DataOutputStream out; 
    static BufferedReader input; 

    static public String get(String _url) 
    { 
     try 
     { 
      url = new URL(_url.replace(" ", "%20")); 

      InputStream input = url.openStream(); 
      StringWriter writer = new StringWriter(); 
      IOUtils.copy(input, writer); 
      return writer.toString(); 

     } 
     catch (Exception e) 
     { 
      return "ERROR: " + e.getMessage(); 
     } 
    } 

    static public String post(String _url, String postData) 
    { 
     String result = ""; 

     try 
     { 
      url = new URL(_url); 

      urlConn = url.openConnection(); 
      urlConn.setDoInput(true); 
      urlConn.setDoOutput(true); 
      urlConn.setUseCaches(false); 
      urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

      out = new DataOutputStream(urlConn.getOutputStream()); 
      String content = postData; 

      out.writeBytes(content); // send the data 

      out.flush(); 
      out.close(); 

      DataInputStream in = new DataInputStream(urlConn.getInputStream()); 
      input = new BufferedReader(new InputStreamReader(in)); 

      String str; 

      while ((str = input.readLine()) != null) 
      { 
       result = result + str + "\n"; 
      } 

      input.close(); 
     } 
     catch (Exception e) 
     { 
      System.err.println(e.toString()); 
      return null; 
     } 

     return result; 
    } 
} 

您也可以使用这个小片段火了在Java Web浏览器 -

URI url = new URI("file:/" + ur); // or an absolute path to a website http://google.com/ 

Desktop.getDesktop().browse(url); 
+0

org.apache.commons.io.IOUtils无法解析,我认为这可能是因为我的eclipse版本。我正在使用Juno –

+1

如果您未使用Maven,请从http://commons.apache.org/io/download_io.cgi下载它,并将下载附带的.jar文件添加到您的构建路径。如果使用Maven,这可能会有所帮助 - http://mvnrepository.com/artifact/commons-lang/commons-lang/2.2 – sircapsalot

+0

好的,谢谢我会试试你的代码 –