显示带有HTTP请求的网页

时间:2012-10-11 16:34:27

标签: java

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

2 个答案:

答案 0 :(得分:1)

你可以使用 java.net.URL, java.net.URLConnection, java.io.InputStream, org.apache.commons.io.IOUtils来管理Java应用程序中的HTTP请求

这是一个示例类 -

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);

答案 1 :(得分:0)

使用

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

另见