通过URL将参数传递给REST Web服务

时间:2010-11-09 14:28:42

标签: rest netbeans

我正在使用Netbeans创建一个小型REST Web服务。这是我的代码:

private UriInfo context;
private String name;

public GenericResource() {
}

@GET
@Produces("text/html")
public String getHtml() {
    //TODO return proper representation object
    return "Hello "+ name;
}


@PUT
@Consumes("text/html")
public void putHtml(String name) {
    this.name = name;
}

我正在调用get方法,因为当我调用http://localhost:8080/RestWebApp/resources/greeting时,我得到“Hello null”但我正在尝试使用http://localhost:8080/RestWebApp/resources/greeting?name=Krt_Malta传递参数,但是没有调用PUT方法。 ..这是传递参数的正确方法还是我错过了什么?

我是Rest bdw的新手,所以如果这是一个简单的问题就可以了。

谢谢! :) Krt_Malta

4 个答案:

答案 0 :(得分:0)

第二个URL是普通的GET请求。要将数据传递给PUT请求,您必须使用表单传递它。据我所知,URL是为GET保留的。

答案 1 :(得分:0)

如果您自己构建HTTP标头,则必须使用POST而不是GET:

GET /RestWebApp/resources/greeting?name=Krt_Malta HTTP/1.0

POST /RestWebApp/resources/greeting?name=Krt_Malta HTTP/1.0

如果您使用HTML表单,则必须将method-attribute设置为“PUT”:

<form action="/RestWebApp/resources/greeting" method="PUT">

答案 2 :(得分:0)

对于JAX-RS要注释使用@PUT注释的方法,您需要提交PUT请求。普通浏览器不会这样做,但可以使用cURL或HTTP客户端库。

要将查询参数映射到方法参数,JAX-RS会提供@QueryParam注释。

public void putWithQueryParam(@QueryParam("name") String name) {
  // do something
}

答案 3 :(得分:0)

您可以设置:

@PUT
@path{/putHtm}
@Consumes("text/html")
public void putHtml(String name) {
    this.name = name;
}

如果你使用google`s Volley库这样的东西,你可以这样做。

        GsonRequest<String> asdf = new GsonRequest<String>(ConnectionProperties.happyhourURL + "/putHtm", String.class, yourString!!, true,
                new Response.Listener<Chain>() {
                    @Override
                    public void onResponse(Chain response) {

                    }
                }, new CustomErrorListener(this));
        MyApplication.getInstance().addToRequestQueue(asdf);

和GsonRequest将如下所示:

public GsonRequest(String url, Class<T> _clazz, T object, boolean needLogin, Listener<T> successListener, Response.ErrorListener errorlistener) {
    super(Method.PUT, url, errorlistener);
    _headers = new HashMap<String, String>();
    this._clazz = _clazz;
    this.successListener = successListener;
    this.needsLogin = needLogin;
    _object = object;
    setTimeout();
}
相关问题