举这个基本的例子:
服务器:
@Path("/your-path")
@RequestScoped
public class JSONService {
private final static String AUTH_TOKEN = "rxxkksdfnnchshs";
@GET
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public Response fetchData(@QueryParam("auth_token") String auth_token) {
if(AUTH_TOKEN.equals(auth_token)){
final String results = "result: the object what you want";
return Response.status(Response.Status.OK).entity(results).build();
}
else{
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}
}
客户:
@ManagedBean(name="your-bean-name")
@RequestScoped
public class ResteasyClient {
private static final String BASE_URI = "http://localhost:8080/your-context/your-rest-path";
private final static String AUTH_TOKEN = "rxxkksdfnnchshs";
ClientRequest webResource;
ClientResponse response;
private String data;
public DBOResteasyClient() {
final String Path = "/your-path";
webResource = new ClientRequest(BASE_URI+Path);
}
@Produces
@Named
public String getData(){
return this.data;
}
@PostConstruct
public void fetchData() {
try{
ClientRequest resource = webResource;
response = resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).queryParameter("auth_token",AUTH_TOKEN).get(ClientResponse.class);
}catch(Exception e ){
//
}
if(response.getStatus() == 200 ){
data = (String) response.getEntity(String.class);
}
}
}
此示例在服务器中使用 @QueryParam("auth_token") String auth_token 获取名为 auth_token 和 resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).queryParameter("auth_token",AUTH_TOKEN) 的 http 请求参数添加一个名为auth_token的参数,关键是:服务器使用该参数并将其与自己的值“(AUTH_TOKEN.equals(auth_token)”进行比较,并用http代码响应rest是如何构建的,http 200 if acept access “(Response.Status .OK)" http 401 如果不是 "(Response.Status.UNAUTHORIZED)"