Java利用RMI实现http请求服务

一、题目描述

编写Java程序,实现RMI远程调用。客户端指定某个http网站,把这个网址传递给服务器端,服务器端提供http下载服务,通过http get 请求访问http网站,把对应的html文件返回给客户端

二、实现思路

1. 客户端

在GUI界面输入访问的网址,按下按钮提交请求
监听按钮点击事件,引用远程访问的类,将处理结果反馈到文本框中

2. 服务器端

定义服务接口,需要继承自Remote类
定义实现服务接口的类,在类中编写业务逻辑,需要继承 UnicastRemoteObject 类
在主函数中注册服务

三、实现过程

1. 客户端

编写基本的GUI界面(不熟。。要是写前端三件套就好了

public class RMIClient extends JFrame {  
  
    public static void main(String[] args) {  
        new RMIClient("Client");  
    }  
    public RMIClient(String var){  
        super(var);  
        this.setSize(1000, 1500);  
        this.setTitle("RAMClient");  

        JPanel jp1 = new JPanel();  
        JLabel jl1 = new JLabel("Please type the URL you want to visit: ");  
        JTextField jt1 = new JTextField(30);  
        JButton jb1 = new JButton("Confirm");  
        jp1.add(jl1);  
        jp1.add(jt1);  
        jp1.add(jb1);  

        JTextArea jTextArea = new JTextArea();  
        jTextArea.setSize(250, 1200);  
        jTextArea.setEditable(false);  
        JScrollPane sp =new JScrollPane();  
        sp.setViewportView(jTextArea);

监听JButton事件,将返回数据逐行添加到JTextArea

        jb1.addActionListener((e)->{  
            String input = jt1.getText();  
            File htmlFile;  
            // lookup method to find reference  
            try{  
                DownloadService access = (DownloadService) Naming.lookup("rmi://localhost:1099/download");  
                htmlFile = access.getHTMLfile(input);  
                if(htmlFile != null){  
                    BufferedReader bufferedReader = new BufferedReader(new FileReader(htmlFile));  
                    String temp = null;  
                    while((temp = bufferedReader.readLine()) != null){  
                        jTextArea.append(temp+'\n');  
                        //System.out.println(temp+'\n');  
                    }  
                    bufferedReader.close();  
                }  
            }catch (Exception err){  
                err.printStackTrace();  
            }  
        });

将组件添加到JFrame中并显示

        this.setLayout(new GridLayout(3, 4));  
        this.add(jp1);  
        this.add(sp);  
        this.setVisible(true);  
        this.pack();  
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    }  
}

2. 服务器端

定义服务接口DownloadService

public interface DownloadService extends Remote {  
    File getHTMLfile(String urlStr) throws RemoteException, MalformedURLException;  
}

定义实现上述接口的服务类

public class DownloadServiceImpl extends UnicastRemoteObject implements DownloadService {  
    protected DownloadServiceImpl() throws RemoteException{  
        super();  
    }  

初始化Http连接对象以及响应文件对象

    @Override  
    public File getHTMLfile(String urlStr) throws RemoteException, MalformedURLException {  
        // initialization  
        File file = new File("result.html");  
        FileWriter fileWriter = null;  
        try {  
            if(!file.exists()){  
                file.createNewFile();  
            }  
            fileWriter = new FileWriter(file);  
        }catch (IOException e){  
            e.printStackTrace();  
        }  
        HttpURLConnection conn = null;  
        InputStream inputStream = null;  
        BufferedReader bufferedReader = null;  

建立连接,逐行读取返回的HTML响应,保存到文件中

      // create connection  
      try{  
          URL url = new URL(urlStr);  
          conn = (HttpURLConnection) url.openConnection();  
          conn.setRequestMethod("GET");  
          conn.setConnectTimeout(12000);  
          conn.connect();  
          System.out.println("Wait for response");  
          if(conn.getResponseCode() == 200){  
              // if conn success  
              inputStream = conn.getInputStream();  
              if (inputStream != null){  
                  bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
                  String temp = null;  
                  while((temp = bufferedReader.readLine())!= null){  
                      fileWriter.write(temp);  
                      fileWriter.write('\n');  
                  }  
                  fileWriter.close();  
              }  
          }  
      }catch (IOException e){  
          e.printStackTrace();  
      }  
      return file;  
  }  
}

在主函数中注册服务

public class RMIServer {  
    public static void main(String[] args){  
        try{  
            DownloadService downloadService = new DownloadServiceImpl();  
            LocateRegistry.createRegistry(1099);  
            Naming.rebind("rmi://localhost:1099/download", downloadService);  
            System.out.println("Server is ready!");  
        }catch (Exception e){  
            e.printStackTrace();  
        }  
    }  
}

三、运行结果

启动服务端

D:\idea project\javaCourrse\javaEX6\javaEX6\src>java RMIdemo/RMIServer
Server is ready!

启动客户端

D:\idea project\javaCourrse\javaEX6\javaEX6\src>java RMIdemo/RMIClient

image.png
输入网址并点击按钮
image.png

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值