使用GWT发送HTTP请求

来源:互联网 发布:淘宝流量高峰期时间段 编辑:程序博客网 时间:2024/05/18 19:43
 

为什么要使用GWTHTTP方式发送请求

GWT本身提供了方便稳定的RPC方式与服务器程序通信,但有些特殊情况我们还是要使用原始的HTTP方式发送请求。

比如:

l  使用GWT发送HTTP请求,服务器端程序不受任务限制,可以是JavaServlet,也可以是PHP脚本等其它服务器端程序。(测试以Java servlet为例)。

l  与服务器端的程序进行JSONXML的交互。

 

GWT如何使用HTTP方式发送请求

GWT发送HTTP请求需要用到RequestBuilder类,该类全路径为:com.google.gwt.http.client.RequestBuilder

注意:使用前必需在模块配置文件(***.gwt.xml)中加入:<inherits name="com.google.gwt.http.HTTP"/>

 

例如:

  1. <module>
  2.     <!-- Inherit the core Web Toolkit stuff.                  -->
  3.     <inherits name='com.google.gwt.user.User'/>
  4.     <!-- Specify the app entry point class.                   -->
  5.     <entry-point class='org.leo.client.GwtHttpTestEntryPoint'/>
  6.   
  7.     <inherits name="com.google.gwt.user.theme.standard.Standard"/>
  8.     
  9.     <inherits name="com.google.gwt.http.HTTP"/>
  10.     
  11. </module>

发送HTTP请求,使用RequestBuildersend()方法或者sendRequest(String requestData, RequestCallback callback)方法。

其中sendRequest(String requestData, RequestCallback callback)方法中的requestDataPOST方式发送的数据,如果是GET方法则可以设置为nullcallback是请求结束后的回调句柄。

使用send()方法前,应该使用setCallback(RequestCallback callback)方法设置回调句柄。如果是POST方式,还应该使用setRequestData(String requestData)方法设置POST要发送的数据。

RequestBuilder的实例化方法为:

         RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

第一个参数是请求类型,可以是POSTGET等。

第二个参数是请求目标的URL

使用RequestBuilder的注意事项:

l  发送请求的目标URL应使用url = URL.encode(url)编码。

l  GET方式发送请求时,参数直接写在URL中,所有参数设置完成后再进行encoderequestData可以设置为null

l  如果使用RemoteServiceServlet类接收请求(或者使用RPCServletUtils类处理请求)则必须设置requestBuilder.setHeader("Content-Type", "text/x-gwt-rpc; charset=utf-8");不能换成别的content-type。最好在setRequestData(String requestData)方法之前设置。

 

例如:

GET方式
 
  1. public class GwtHttpTestEntryPoint implements EntryPoint {
  2.     private final String BASIC_URL = "http://localhost:8080/xxxServer/jsonTest";
  3.     private TextBox text = new TextBox();
  4.     private Button btn = new Button("Http Request Test");
  5.     private Label lbl = new Label("");
  6.     public void onModuleLoad() {
  7.         RootPanel.get().add(text);
  8.         RootPanel.get().add(btn);
  9.         RootPanel.get().add(lbl);
  10.         btn.addClickListener(new ClickListener(){
  11.             public void onClick(Widget sender) {
  12.                 btn.setEnabled(false);
  13.                 String url = BASIC_URL + "?txt=" + text.getText();
  14.                 url = URL.encode(url);
  15.                 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
  16. //              builder.setHeader("Content-Type", "text/x-gwt-rpc; charset=utf-8");
  17.                 builder.setCallback(new RequestCallback(){
  18.                     public void onError(Request request, Throwable exception) {
  19.                         // TODO Auto-generated method stub
  20.                         btn.setEnabled(true);
  21.                     }
  22.                     public void onResponseReceived(Request request, Response response) {
  23.                         // TODO Auto-generated method stub
  24.                         if(200 == response.getStatusCode()){
  25.                             lbl.setText(response.getText());
  26.                         }else{
  27.                             //error
  28.                         }
  29.                         btn.setEnabled(true);
  30.                     }
  31.                 });
  32.                 //发送
  33.                 try {
  34.                     builder.send();
  35.                 } catch (RequestException e) {
  36.                     e.printStackTrace();
  37.                 }
  38.             }
  39.         });
  40.         
  41.     }
  42. }
POST
方式
  1. public class GwtHttpTestEntryPoint implements EntryPoint {
  2.     private final String BASIC_URL = "http://localhost:8080/xxxServer/jsonTest";
  3.     private TextBox text = new TextBox();
  4.     private Button btn = new Button("Http Request Test");
  5.     private Label lbl = new Label("");
  6.     public void onModuleLoad() {
  7.         RootPanel.get().add(text);
  8.         RootPanel.get().add(btn);
  9.         RootPanel.get().add(lbl);
  10.         btn.addClickListener(new ClickListener(){
  11.             public void onClick(Widget sender) {
  12.                 btn.setEnabled(false);
  13.                 RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, BASIC_URL);
  14.                 builder.setHeader("Content-Type""text/x-gwt-rpc; charset=utf-8");
  15.                 builder.setRequestData(text.getText());
  16.                 builder.setCallback(new RequestCallback(){
  17.                     public void onError(Request request, Throwable exception) {
  18.                         // TODO Auto-generated method stub
  19.                         btn.setEnabled(true);
  20.                     }
  21.                     public void onResponseReceived(Request request, Response response) {
  22.                         // TODO Auto-generated method stub
  23.                         if(200 == response.getStatusCode()){
  24.                             lbl.setText(response.getText());
  25.                         }else{
  26.                             //error
  27.                         }
  28.                         btn.setEnabled(true);
  29.                     }
  30.                 });
  31.                 //发送
  32.                 try {
  33.                     builder.send();
  34.                 } catch (RequestException e) {
  35.                     e.printStackTrace();
  36.                 }
  37.             }
  38.         });
  39.     }
  40. }
Servlet代码:
  1. public class JsonTest extends HttpServlet {
  2.     private static final long serialVersionUID = 1L;
  3.     /**
  4.      * Default constructor. 
  5.      */
  6.     public JsonTest() {
  7.         // TODO Auto-generated constructor stub
  8.     }
  9.     @Override
  10.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  11.             throws ServletException, IOException {
  12.         String s = req.getParameter("txt");
  13.         String str = new String(s.getBytes("iso8859-1"),"utf-8");
  14.         
  15.         System.out.println("client [get]:" + str);
  16.         resp.setCharacterEncoding("utf-8");
  17.         resp.getWriter().write("server message!!!!" + str);
  18.         
  19.     }
  20.     @Override
  21.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  22.             throws ServletException, IOException {
  23.             throws ServletException, IOException {
  24.         //使用GWT RPCServletUtils
  25.         String  str = RPCServletUtils.readContentAsUtf8(req, true);
  26.         /*
  27.         //或者手工处理POST流 
  28.         String str;
  29.         int contentLength = req.getContentLength();
  30.         if (contentLength == -1) {
  31.           throw new ServletException("Content is null");
  32.         }
  33.         InputStream in = req.getInputStream();
  34.         try {
  35.           byte[] buff = new byte[contentLength];
  36.           int offset = 0;
  37.           int len = contentLength;
  38.           int byteCount;
  39.           while (offset < contentLength) {
  40.             byteCount = in.read(buff, offset, len);
  41.             if (byteCount == -1) {
  42.               throw new ServletException("did not send");
  43.             }
  44.             offset += byteCount;
  45.             len -= byteCount;
  46.           }
  47.           str = new String(buff, "UTF-8");
  48.         } finally {
  49.           if (in != null) {
  50.             in.close();
  51.           }
  52.         }
  53.         */
  54.         System.out.println("client [post]:" + str);
  55.         resp.setCharacterEncoding("utf-8");
  56.         resp.getWriter().write("server message!!!!" + str);
  57.     }

POST方式发送可以传送较大内容,避免乱码现象,最好使用POST方式发送。如果在客户端和服务器端都使用XMLJSON,则可以很方便的实现用对象来交换数据。

 

传递多个值不使用GWT RRCServletUtil 处理POST请求

使用GET方式传递多个值的时候只需在URL后以&分隔,加上多个键值对即可。

如果使用POST方式发送多个值时,也要以 --- 对的方式发送POST内容。设置请求数据内容时应按以下格式:

       builder.setRequestData("userName=leo&psd=123");

注意多个 -- 对应该以&分隔。

要注意的是,这个时候应该把ContentType设置为 application/x-www-form-urlencoded

例如:

builder.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

这样就可以在Servlet中,通过getParameter方法,简单取得传递的值。

 

中文及乱码的处理

传递ASCII码表以外的字符时会出现乱码,所以我们应该使用更大的字符集,如Unicode编码集,最常用的是UTF-8Unicode实现。

使用GET方式传递,前台页面只要使用URL.encodeURL进行编码即可。后台在使用getParameter取得传递的值时,应使用

String str = new String(value.getBytes("iso8859-1"),"utf-8");

注意,是否必需使用该语句,取决于使用的服务器,在Tomcat中测试,如果不使用就有机会出现乱码。

GET方式有效大的局限性,如因IEURL的长度限制,GET方式只能传递2K+35字节(2083)。其它浏览器,理论上没有限制,但也取决于操作系统的支持。以及GET安全性非常低等。我们通常使用POST方式传递数据,使用POST方式传递数据时,注意前台页面上的ContentType设置,应该设置为UTF-8,在后台Servlet中直接使用 getParameter 方法即可。

 

原创粉丝点击