2012-08-17 90 views
0

我的客户端没有实现HttpServlet接口。它连接到一个远程运行的HttpServletJava - 客户端如何获得来自HttpServlet的响应

url = new URL("http://tomcat-location:8180/myContext"); 

这是它用来发送消息到servlet的。但是它怎样才能得到回应呢?当我尝试从这个位置读取时,我正在阅读指定页面的内容。也许我的整个方法是错误的,这不是客户端和servlet应该如何相互交流的方式?我怎样才能让他们以简单的方式谈话?似乎使用URL,他们通过发布和阅读该页面进行通信。有没有其他的方式可以在网页上书写而不用写? 感谢

+0

你想阅读'http:// tomcat-location:8180/myContext'返回的内容吗? – davidbuzatto 2012-08-17 03:42:52

+0

是的,我想读取什么是servlet响应。基本上,servlet管理两个客户端之间的对话:client1向servlet说了些什么,然后servlet以规则的,交替的方式将其转发给client2,等等。 – Trup 2012-08-17 03:47:37

+0

没有HttpServlet接口。这是一个抽象类。客户永远不会延伸它。 Servlets呢。 Servlet和HTTP URL通过GET和POST请求进行通信。你的问题仍然不清楚。 – EJP 2012-08-17 09:48:52

回答

0

试试这个:

public static String getURLData(String url) { 

    // creates a StringBuilder to store the data 
    StringBuilder out = new StringBuilder(); 

    try { 

     // creating the URL 
     URL u = new URL(url); 

     // openning a connection 
     URLConnection uCon = u.openConnection(); 

     // getting the connection's input stream 
     InputStream in = uCon.getInputStream(); 

     // a buffer to store the data 
     byte[] buffer = new byte[2048]; 


     // try to insert data in the buffer until there is data to be read 
     while (in.read(buffer) != -1) { 

      // storing data... 
      out.append(new String(buffer)); 

     } 

     // closing the input stream 
     in.close();    

     // exceptions... 
    } catch (MalformedURLException exc) { 

     exc.printStackTrace(); 

    } catch (IOException exc) { 

     exc.printStackTrace(); 

    } catch (SecurityException exc) { 

     exc.printStackTrace(); 

    } catch (IllegalArgumentException exc) { 

     exc.printStackTrace(); 

    } catch (UnsupportedOperationException exc) { 

     exc.printStackTrace(); 

    } 

    // returning data 
    return out.toString(); 

} 

如果需要使用代理,你需要做更多的工作,因为你将需要验证工作。在这里,你可以阅读一些事情:How do I make HttpURLConnection use a proxy?

如果你想有一个客户端,就像一个浏览器,你可以从Apache HttpComponentes

尝试HttpClient的现在,如果你需要在服务器通知客户端行为,所以您需要使用其他方法,例如创建自己的服务器并使用套接字。如果你使用普通的浏览器工作,你可以使用websockets,但它似乎不是你的情况。

+0

我的意图是让servlet管理2个客户端之间的对话:client1向servlet说了些什么,然后servlet以规则的,交替的方式将其转发给client2,等等。你的方法是否适用于此目的? – Trup 2012-08-17 03:51:39

+0

我的方法只会获取数据。如果你想要一个像浏览器一样工作的客户端,你可以尝试[Apache HttpComponentes](http://hc.apache.org/httpcomponents-client-ga/)中的HttpClient, – davidbuzatto 2012-08-17 03:54:13