我想在RESTful WS @OPTION注释中使用它作为帮助。我在http://www.programcreek.com/java-api-examples/index.php?source_dir=AIDR-master/aidr-output/src/main/java/qa/qcri/aidr/output/getdata/GetBufferedAIDRData.java找到了一个代码段。有一段代码:
@OPTIONS
@Produces(MediaType.APPLICATION_JSON)
@Path("/channel/filter/{crisisCode}")
public Response getBufferedAIDRDataPostFilter(@PathParam("crisisCode") String channelCode,
@QueryParam("callback") String callbackName,
@DefaultValue("1000") @QueryParam("count") int count) {
return Response.ok()
.allow("POST", "GET", "PUT", "UPDATE", "OPTIONS", "HEAD")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS, HEAD")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
.build();
}
但是我没有找到,如何从客户端上面的定义中调用并获取标题内容等。
答案 0 :(得分:1)
由于您在JaxRS REST API实现中发布的代码段,因此下面提供的解决方案也是JaxRS客户端实现。 这可以使用任何框架以任何语言实现,但这取决于您的要求。
以下是一个代码片段,用于在REST API端点上调用OPTIONS请求并处理其响应。
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
public class RestClient {
public static void main(String[] args) {
Client client = ClientBuilder.newBuilder().build();
WebTarget target = client.target("https://<api-base-url>/<resource-path>");
Response response = target.request().options();
Map<String, List<String>> headerMap = response.getStringHeaders();
for (String key : headerMap.keySet()) {
List<String> values = headerMap.get(key);
for (String value : values) {
// The header and its corresponding value can be processed as per the case.
}
}
// This will return a list of all supported HTTP Methods (GET, POST, PUT, ..., etc)
List<String> httpMethods = headerMap.get("Allow");
for (String method : httpMethods) {
if ("GET".equals(method)) {
// Do something
}
if ("POST".equals(method)) {
// Do something
}
...
...
}
response.close();
}
}
Response类可能会有更多方法,可以根据实现需要进行探索。