[英]play framework- how to send post request using java code in play framework
目前我正在轉向開發框架來開發,但我是這個奇妙框架的新手。 我只想向遠程服務器發送一個帖子請求並獲得響應。
如果我使用澤西島,那將很容易,就像這樣:
WebResource resource = client.resource("http://myfirstUrl");
resource.addFilter(new LoggingFilter());
Form form = new Form();
form.add("grant_type", "authorization_code");
form.add("client_id", "myclientId");
form.add("client_secret", "mysecret");
form.add("code", "mycode");
form.add("redirect_uri", "http://mysecondUrl");
String msg = resource.accept(MediaType.APPLICATION_JSON).post(String.class, form);
然后我可以得到我想要的消息。
但是在Play框架中,我找不到任何libs來發送這樣的帖子請求。 我相信這應該是一個非常簡單的功能,Play應該集成它。 我試圖搜索並發現大多數用例都是關於視圖級別的表單。 誰能給我一些幫助或例子? 提前致謝!
您可以使用Play WS API在Play應用程序中進行異步HTTP調用。 首先,您應該添加javaWs
作為依賴項。
libraryDependencies ++= Seq(
javaWs
)
然后制作HTTP POST請求就像這樣簡單;
WS.url("http://myposttarget.com")
.setContentType("application/x-www-form-urlencoded")
.post("key1=value1&key2=value2");
post()
和其他http方法返回一個F.Promise<WSResponse>
對象,這是從Play Scala繼承到Play Java的東西。 基本上它是異步調用的基礎機制。 您可以按如下方式處理和獲取請求的結果:
Promise<String> promise = WS.url("http://myposttarget.com")
.setContentType("application/x-www-form-urlencoded")
.post("key1=value1&key2=value2")
.map(
new Function<WSResponse, String>() {
public String apply(WSResponse response) {
String result = response.getBody();
return result;
}
}
);
最后獲得的promise
對象是我們案例中String
對象的包裝器。 你可以把包裝好的String
作為:
long timeout = 1000l;// 1 sec might be too many for most cases!
String result = promise.get(timeout);
timeout
是等待此異步請求被視為失敗的等待時間。
有關更詳細的說明和更高級的用例,請查看文檔和javadoc。
https://www.playframework.com/documentation/2.3.x/JavaWS
https://www.playframework.com/documentation/2.3.x/api/java/index.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.