将HTML表单发送到Restlet

3

我有一个需要提交到restlethtml表单。看起来很简单,但是表单总是返回空白。

这是表单:

<form action="/myrestlet" method="post"> 
    <input type="text" size=50 value=5/>
    <input type="text" size=50 value=C:\Temp/>
    (and a few other input type texts)
</form>

Restlet

@Post
public Representation post(Representation representation) {
    Form form = getRequest().getResourceRef().getQueryAsForm();
    System.out.println("form " + form);
    System.out.println("form size " + form.size());
}

我也尝试过获取这样的表单:
Form form = new Form(representation);

但总是以大小为0的[]形式出现。

我错过了什么?

编辑:这是我正在使用的解决方法:

String query = getRequest().getEntity().getText();

这里包含了form的所有值。我需要解析它们,虽然有些烦人,但可以完成工作。

请求参数缺失。 - Roman C
@RomanC 你能详细说明一下吗? - Eddy
不,我不熟悉上面的代码,我只是在HTML代码中看到了一些错别字。 - Roman C
HTML 中有哪些错别字? - Eddy
错别字只是没有引号的值。 - Roman C
2个回答

3
以下是在Restlet服务器资源中获取提交的HTML表单值的正确方法(使用内容类型 application/x-www-form-urlencoded)。这实际上就是你所做的。
public class MyServerResource extends ServerResource {
    @Post
    public Representation handleForm(Representation entity) {
        Form form = new Form(entity);

        // The form contains input with names "user" and "password"
        String user = form.getFirstValue("user");
        String password = form.getFirstValue("password");

        (...)
    }
}

在您的情况下,HTML表单实际上未发送,因为您没有为表单定义任何属性name。我使用了您的HTML代码,但发送的数据为空。您可以使用Chrome开发者工具(Chrome)或Firebug(Firefox)进行检查。
POST /myrestlet HTTP/1.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Connection: keep-alive
Host: localhost:8182
Referer: http://localhost:8182/static/test.html
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0
Content-Length: 0
Content-Type: application/x-www-form-urlencoded

您应该为您的HTML表单使用类似于以下内容的代码:
<form action="/test" method="post">
  <input type="text" name="val1" size="50" value="5"/>
  <input type="text" name="val2" size="50" value="C:\Temp"/>
  (and a few other input type texts)
  <input type="submit" value="send">
</form>

在这种情况下,请求将是:

POST /myrestlet HTTP/1.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Connection: keep-alive
Host: localhost:8182
Referer: http://localhost:8182/static/test.html
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0
Content-Length: 23
Content-Type: application/x-www-form-urlencoded

val1=5&val2=C%3A%5CTemp

希望这能对你有所帮助,Thierry。

谢谢,现在它可以工作了。只是为了澄清,我需要给输入字段命名,而不是表单本身。 - Eddy

2

这里有一个更简单的方法来实现这个,它直接将表单声明为Java方法的参数:

public class MyServerResource extends ServerResource {
    @Post
    public Representation handleForm(Form form) {

        // The form contains input with names "user" and "password"
        String user = form.getFirstValue("user");
        String password = form.getFirstValue("password");

    (...)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接