为什么要使用GWT的HTTP方式发送请求
GWT本身提供了方便稳定的RPC方式与服务器程序通信,但有些特殊情况我们还是要使用原始的HTTP方式发送请求。
比如:
l 使用GWT发送HTTP请求,服务器端程序不受任务限制,可以是Java的Servlet,也可以是PHP脚本等其它服务器端程序。(测试以Java servlet为例)。
l 与服务器端的程序进行JSON或XML的交互。
GWT如何使用HTTP方式发送请求
GWT发送HTTP请求需要用到RequestBuilder类,该类全路径为:com.google.gwt.http.client.RequestBuilder。
注意:使用前必需在模块配置文件(***.gwt.xml)中加入:<inherits name="com.google.gwt.http.HTTP"/>
例如:
- <module>
- <!-- Inherit the core Web Toolkit stuff. -->
- <inherits name='com.google.gwt.user.User'/>
- <!-- Specify the app entry point class. -->
- <entry-point class='org.leo.client.GwtHttpTestEntryPoint'/>
- <inherits name="com.google.gwt.user.theme.standard.Standard"/>
- <inherits name="com.google.gwt.http.HTTP"/>
- </module>
发送HTTP请求,使用RequestBuilder的send()方法或者sendRequest(String requestData, RequestCallback callback)方法。
其中sendRequest(String requestData, RequestCallback callback)方法中的requestData为POST方式发送的数据,如果是GET方法则可以设置为null。callback是请求结束后的回调句柄。
使用send()方法前,应该使用setCallback(RequestCallback callback)方法设置回调句柄。如果是POST方式,还应该使用setRequestData(String requestData)方法设置POST要发送的数据。
RequestBuilder的实例化方法为:
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
第一个参数是请求类型,可以是POST或GET等。
第二个参数是请求目标的URL。
使用RequestBuilder的注意事项:
l 发送请求的目标URL应使用url = URL.encode(url)编码。
l GET方式发送请求时,参数直接写在URL中,所有参数设置完成后再进行encode,requestData可以设置为null。
l 如果使用RemoteServiceServlet类接收请求(或者使用RPCServletUtils类处理请求)则必须设置requestBuilder.setHeader("Content-Type", "text/x-gwt-rpc; charset=utf-8");不能换成别的content-type。最好在setRequestData(String requestData)方法之前设置。
例如:
GET方式
- public class GwtHttpTestEntryPoint implements EntryPoint {
- private final String BASIC_URL = "http://localhost:8080/xxxServer/jsonTest";
- private TextBox text = new TextBox();
- private Button btn = new Button("Http Request Test");
- private Label lbl = new Label("");
- public void onModuleLoad() {
- RootPanel.get().add(text);
- RootPanel.get().add(btn);
- RootPanel.get().add(lbl);
- btn.addClickListener(new ClickListener(){
- public void onClick(Widget sender) {
- btn.setEnabled(false);
- String url = BASIC_URL + "?txt=" + text.getText();
- url = URL.encode(url);
- RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
- // builder.setHeader("Content-Type", "text/x-gwt-rpc; charset=utf-8");
- builder.setCallback(new RequestCallback(){
- public void onError(Request request, Throwable exception) {
- // TODO Auto-generated method stub
- btn.setEnabled(true);
- }
- public void onResponseReceived(Request request, Response response) {
- // TODO Auto-generated method stub
- if(200 == response.getStatusCode()){
- lbl.setText(response.getText());
- }else{
- //error
- }
- btn.setEnabled(true);
- }
- });
- //发送
- try {
- builder.send();
- } catch (RequestException e) {
- e.printStackTrace();
- }
- }
- });
-
- }
- }
POST方式
- public class GwtHttpTestEntryPoint implements EntryPoint {
- private final String BASIC_URL = "http://localhost:8080/xxxServer/jsonTest";
- private TextBox text = new TextBox();
- private Button btn = new Button("Http Request Test");
- private Label lbl = new Label("");
- public void onModuleLoad() {
- RootPanel.get().add(text);
- RootPanel.get().add(btn);
- RootPanel.get().add(lbl);
- btn.addClickListener(new ClickListener(){
- public void onClick(Widget sender) {
- btn.setEnabled(false);
- String url = BASIC_URL + "?txt=" + text.getText();
- url = URL.encode(url);
- RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
- // builder.setHeader("Content-Type", "text/x-gwt-rpc; charset=utf-8");
- builder.setCallback(new RequestCallback(){
- public void onError(Request request, Throwable exception) {
- // TODO Auto-generated method stub
- btn.setEnabled(true);
- }
- public void onResponseReceived(Request request, Response response) {
- // TODO Auto-generated method stub
- if(200 == response.getStatusCode()){
- lbl.setText(response.getText());
- }else{
- //error
- }
- btn.setEnabled(true);
- }
- });
- //发送
- try {
- builder.send();
- } catch (RequestException e) {
- e.printStackTrace();
- }
- }
- });
- }
- }
- public class GwtHttpTestEntryPoint implements EntryPoint {
- private final String BASIC_URL = "http://localhost:8080/xxxServer/jsonTest";
- private TextBox text = new TextBox();
- private Button btn = new Button("Http Request Test");
- private Label lbl = new Label("");
- public void onModuleLoad() {
- RootPanel.get().add(text);
- RootPanel.get().add(btn);
- RootPanel.get().add(lbl);
- btn.addClickListener(new ClickListener(){
- public void onClick(Widget sender) {
- btn.setEnabled(false);
- RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, BASIC_URL);
- builder.setHeader("Content-Type", "text/x-gwt-rpc; charset=utf-8");
- builder.setRequestData(text.getText());
- builder.setCallback(new RequestCallback(){
- public void onError(Request request, Throwable exception) {
- // TODO Auto-generated method stub
- btn.setEnabled(true);
- }
- public void onResponseReceived(Request request, Response response) {
- // TODO Auto-generated method stub
- if(200 == response.getStatusCode()){
- lbl.setText(response.getText());
- }else{
- //error
- }
- btn.setEnabled(true);
- }
- });
- //发送
- try {
- builder.send();
- } catch (RequestException e) {
- e.printStackTrace();
- }
- }
- });
- }
- }
Servlet代码:
- public class JsonTest extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * Default constructor.
- */
- public JsonTest() {
- // TODO Auto-generated constructor stub
- }
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- String s = req.getParameter("txt");
- String str = new String(s.getBytes("iso8859-1"),"utf-8");
-
- System.out.println("client [get]:" + str);
- resp.setCharacterEncoding("utf-8");
- resp.getWriter().write("server message!!!!" + str);
-
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- throws ServletException, IOException {
- //使用GWT RPCServletUtils
- String str = RPCServletUtils.readContentAsUtf8(req, true);
- /*
- //或者手工处理POST流
- String str;
- int contentLength = req.getContentLength();
- if (contentLength == -1) {
- throw new ServletException("Content is null");
- }
- InputStream in = req.getInputStream();
- try {
- byte[] buff = new byte[contentLength];
- int offset = 0;
- int len = contentLength;
- int byteCount;
- while (offset < contentLength) {
- byteCount = in.read(buff, offset, len);
- if (byteCount == -1) {
- throw new ServletException("did not send");
- }
- offset += byteCount;
- len -= byteCount;
- }
- str = new String(buff, "UTF-8");
- } finally {
- if (in != null) {
- in.close();
- }
- }
- */
- System.out.println("client [post]:" + str);
- resp.setCharacterEncoding("utf-8");
- resp.getWriter().write("server message!!!!" + str);
- }
POST方式发送可以传送较大内容,避免乱码现象,最好使用POST方式发送。如果在客户端和服务器端都使用XML或JSON,则可以很方便的实现用对象来交换数据。
传递多个值不使用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-8的Unicode实现。
使用GET方式传递,前台页面只要使用URL.encode对URL进行编码即可。后台在使用getParameter取得传递的值时,应使用
String str = new String(value.getBytes("iso8859-1"),"utf-8");
注意,是否必需使用该语句,取决于使用的服务器,在Tomcat中测试,如果不使用就有机会出现乱码。
但GET方式有效大的局限性,如因IE对URL的长度限制,GET方式只能传递2K+35字节(2083)。其它浏览器,理论上没有限制,但也取决于操作系统的支持。以及GET安全性非常低等。我们通常使用POST方式传递数据,使用POST方式传递数据时,注意前台页面上的ContentType设置,应该设置为UTF-8,在后台Servlet中直接使用 getParameter 方法即可。
- public class JsonTest extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * Default constructor.
- */
- public JsonTest() {
- // TODO Auto-generated constructor stub
- }
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- String s = req.getParameter("txt");
- String str = new String(s.getBytes("iso8859-1"),"utf-8");
- System.out.println("client [get]:" + str);
- resp.setCharacterEncoding("utf-8");
- resp.getWriter().write("server message!!!!" + str);
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- throws ServletException, IOException {
- //使用GWT RPCServletUtils
- String str = RPCServletUtils.readContentAsUtf8(req, true);
- /*
- //或者手工处理POST流
- String str;
- int contentLength = req.getContentLength();
- if (contentLength == -1) {
- throw new ServletException("Content is null");
- }
- InputStream in = req.getInputStream();
- try {
- byte[] buff = new byte[contentLength];
- int offset = 0;
- int len = contentLength;
- int byteCount;
- while (offset < contentLength) {
- byteCount = in.read(buff, offset, len);
- if (byteCount == -1) {
- throw new ServletException("did not send");
- }
- offset += byteCount;
- len -= byteCount;
- }
- str = new String(buff, "UTF-8");
- } finally {
- if (in != null) {
- in.close();
- }
- }
- */
- System.out.println("client [post]:" + str);
- resp.setCharacterEncoding("utf-8");
- resp.getWriter().write("server message!!!!" + str);
- }