2010-11-09 124 views
3

我正在使用Netbeans創建一個小型REST Web服務。這是我的代碼:通過URL將參數傳遞給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空」,但我想用http://localhost:8080/RestWebApp/resources/greeting?name=Krt_Malta傳遞一個參數,但PUT方法不會被調用...這是傳遞參數的正確方法還是我錯過了一些東西?

我是一個新手休息bdw,所以如果這是一個簡單的問題。

謝謝! :) Krt_Malta

+0

你在使用調用網址嗎?你有沒有試過curl -X PUT http:// ...? – xwoker 2013-09-23 11:08:14

回答

0

第二個URL是一個普通的GET請求。要將數據傳遞給PUT請求,您必須使用表單傳遞它。就我所知,URL保留爲GET。

0

如果你自己構建的HTTP標頭,則必須使用POST而不是GET:如果您使用HTML格式的

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

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

,你必須設置方法 - 屬性爲 「PUT」:

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

對於JAX-RS以mactch與@PUT註釋的方法,你需要提交PUT請求。普通瀏覽器不這樣做,但可以使用cURL或HTTP客戶端庫。

要將查詢參數映射到方法參數,JAX-RS提供了@QueryParam註釋。

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

您可以設置:

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

,如果你使用類似google`s凌空庫,你可以做。

 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(); 
}