![](/img/trans.png)
[英]Java Restful Web Service using Jersey implementation developed in Eclipse IDE not deployed and call on JBoss server
[英]How to simulate client-server restful web service completely in Java IDE, without deploying to a web server, using jersey?
我什至不可能做到這一點,這就是為什么我以為會問。
我忘了提到我正在使用Jersey 1.19和Java 1.6。
我使用Jersey API用Java創建了RESTful Web服務以及用於調用Web服務的客戶端代碼。 客戶端代碼也是基於Jersey的。 我遇到的問題是,我不想每次進行更改並要測試時都將JAR文件部署到Web服務器上-Web服務器位於遠程服務器上,而我正在本地編碼電腦。
是否可以在IDE(即Eclipse)中完全模擬客戶端-服務器Web服務調用? 換句話說,我想從本地計算機調用Web服務,而不必將其托管在Web服務器上。 與調用函數沒有什么不同。
這是客戶端代碼:
package com.xyzcorp.webservices;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class RestClient {
public static void main(String[] args) {
Client client = Client.create();
/*
Right now, it's calling the web service on the web server.
I want to call this same web service but from within the code local
to my computer, without hosting it on a web server.
*/
WebResource webResource = client.resource("http://myserver.com/rest/ids/12345");
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
}
}
這是Web服務代碼:
package com.xyzcorp.webservices;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.xyzcorp.webservices.EmpData;
@Path("/rest")
public class RestWebService {
@GET
@Path("/ids/{ids}")
@Produces(MediaType.APPLICATION_JSON)
public EmpData getEmpDataJSON(
@PathParam("ids") String ids)
...
return empData;
}
}
是否可以在不使用Web服務器的情況下直接調用RestWebService
類? 即`WebResource webResource = client.resource(new RestWebService()。EmpData(“ 12345”));
非常感謝你。
使用Jersey測試框架 。 像正常的單元測試一樣,對資源運行(半)集成/單元測試。 例如
public class MainTest extends JerseyTest {
public MainTest() throws Exception {
super("com.sun.jersey.samples.helloworld.resources");
}
@Test
public void testHelloWorld() {
WebResource webResource = resource();
String responseMsg = webResource.path("helloworld").get(String.class);
assertEquals("Hello World", responseMsg);
}
}
JerseyTest將為每個測試用例啟動和停止嵌入式服務器。 根據您要使用的服務器依賴性,它甚至可以是內存中的服務器(以免花費太多的加載時間)。 這是一個示例依賴項
<dependency>
<groupId>com.sun.jersey.jersey-test-framework</groupId>
<artifactId>jersey-test-framework-grizzly2</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
我提供的鏈接顯示了您可以使用的其他依賴項。
這是另一個用法示例 (底部是澤西島1.x,頂部是2.x)
這可能對您有用: http : //www.eclipse.org/webtools/community/education/web/t320/Implementing_a_Simple_Web_Service.pdf
特別是第12頁起。 希望能幫助到你。
編輯:以防萬一,您的計算機URL將包含用於在本地計算機上運行的服務的“ localhost”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.