我们正在使用jersey(1.9.1)和tomcat 5.5开发一个restful api.给定资源用urn标识,我们想要解决该资源的特定实例.为了实现这一点,我们使用了以下代码:
@Path("/XXXs")
public interface XXXResource {
@GET
@Path("{id}")
@Produces({ MediaType.APPLICATION_JSON })
XXXInfo getXXX(@PathParam("id") String id);
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是使用以下URL来解决此资源:
HTTP://本地主机:8080/RESTAPI/XXX秒/ HTTP%3A%2F%2Fns.something.com%2FXXX%2F2
解码的路径参数值应为:http: //ns.something.com/XXX/2
但是,当我使用编码的url发出请求时,我从tomcat收到一条错误的请求消息.所以我的问题是:
为了以防万一,我更改了方法的签名,以便从查询字符串中获取参数,并且它工作正常,但我希望参数成为路径的一部分.
谢谢.
这是我要求卷曲的服务:
time curl -i -XPOST 'http://localhost:9080/my/service' -H "Authorization:OAuth MyToken" -H "Content-Type: application/json" -d "ids=516816b2e4b039526a235e2f,516816b2e4b039526a235e2f"
Run Code Online (Sandbox Code Playgroud)
资源:
@Path("/my")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json", "text/json"})
@Restricted
public class MyResource {
@POST
@Path("/service")
public Map<String ,Object> myService(@FormParam("ids") String myIds) {
// service things
}
}
Run Code Online (Sandbox Code Playgroud)
该服务运行良好,但它突然失败了.现在参数myIds总是为null,而curl的结果是400个错误的请求...我没有更改此资源中的任何内容,因此它应该仍然有效.如果有人有想法,请告诉我.谢谢!
我正在尝试使用Jersey 2.0为Dropbox实现REST Client.
为了上传文件,我使用以下代码:
WebTarget target = client.target(targetUrl);
final FileDataBodyPart filePart = new FileDataBodyPart("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE);
final MultiPart multipart = new FormDataMultiPart().bodyPart(filePart);
Response response = target.request(MediaType.APPLICATION_JSON_TYPE).put(Entity.entity(multipart, multipart.getMediaType()));
Run Code Online (Sandbox Code Playgroud)
但是,此代码不起作用并MessageBodyProviderNotFoundException发生在该put方法中.
我怎样才能避免MessageBodyProviderNotFoundException在put方法中.
发生异常时,这是堆栈跟踪:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=multipart/form-data, type=class org.glassfish.jersey.media.multipart.FormDataMultiPart, genericType=class org.glassfish.jersey.media.multipart.FormDataMultiPart.
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:191)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:139)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1005)
at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:430)
at org.glassfish.jersey.client.HttpUrlConnector._apply(HttpUrlConnector.java:287)
at org.glassfish.jersey.client.HttpUrlConnector.apply(HttpUrlConnector.java:200)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:215)
at …Run Code Online (Sandbox Code Playgroud) 我似乎有依赖冲突,我不确定如何解决.我正在尝试将Swagger实现到我的应用程序中.我已经包括了我的pom以及堆栈跟踪.如果我可以包含其他任何内容以更好地描述问题,请告诉我.我不确定如何开始调试这个......
Exception in thread "main" java.lang.NoSuchMethodError: com.sun.jersey.core.reflection.ReflectionHelper.getOsgiRegistryInstance()Lcom/sun/jersey/core/osgi/OsgiRegistry;
at com.sun.jersey.spi.scanning.AnnotationScannerListener$AnnotatedClassVisitor.getClassForName(AnnotationScannerListener.java:217)
at com.sun.jersey.spi.scanning.AnnotationScannerListener$AnnotatedClassVisitor.visitEnd(AnnotationScannerListener.java:186)
at org.objectweb.asm.ClassReader.accept(Unknown Source)
at org.objectweb.asm.ClassReader.accept(Unknown Source)
at com.sun.jersey.spi.scanning.AnnotationScannerListener.onProcess(AnnotationScannerListener.java:136)
at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner$1.f(FileSchemeScanner.java:86)
at com.sun.jersey.core.util.Closing.f(Closing.java:71)
at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scanDirectory(FileSchemeScanner.java:83)
at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scan(FileSchemeScanner.java:71)
at com.sun.jersey.core.spi.scanning.PackageNamesScanner.scan(PackageNamesScanner.java:223)
at com.sun.jersey.core.spi.scanning.PackageNamesScanner.scan(PackageNamesScanner.java:139)
at com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:80)
at com.sun.jersey.api.core.PackagesResourceConfig.init(PackagesResourceConfig.java:104)
at com.sun.jersey.api.core.PackagesResourceConfig.<init>(PackagesResourceConfig.java:78)
at com.api.Main.startServer(Main.java:30)
at com.api.Main.main(Main.java:52)
Run Code Online (Sandbox Code Playgroud)
的pom.xml
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.glassfish.grizzly</groupId>
<artifactId>grizzly-http-servlet</artifactId>
<version>2.2.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.23</version>
</dependency>
<!-- …Run Code Online (Sandbox Code Playgroud) (我是java世界的新手)
我正在学习dropwizard,我想创建返回视图(html)或json的资源,具体取决于请求类型(ajax与否)
例:
@Path("/")
public class ServerResource {
@GET
@Produces(MediaType.TEXT_HTML)
public MainView getMainView() {
return new MainView("Test hello world");
}
}
Run Code Online (Sandbox Code Playgroud)
如果请求是AJAX,如何在相同的Path JSON响应中添加到此资源?
更新1. 我创建了这样的东西:
@Path("/")
public class ServerResource {
@GET
@Consumes(MediaType.TEXT_HTML)
@Produces(MediaType.TEXT_HTML)
public MainView getMainView(@HeaderParam("X-Requested-With") String requestType) {
return new MainView("hello world test!");
}
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<String> getJsonMainView() {
List<String> list = new ArrayList<String>();
for (Integer i = 0; i < 10; i++) {
list.add(i, "test" + i.toString());
}
return list;
}
}
Run Code Online (Sandbox Code Playgroud)
看起来这是按预期工作,但我知道这不是一个好习惯.
当我向服务器发送请求时
...
Response response = builder.method(req.getMethod(), Entity.entity(req, req.getMediaType())); // req.getMediaType() return MediaType.APPLICATION_XML
if(response.getStatus() != 200)
throw new CoreErrorException("core resulted error with status = " + response.getStatus());
T resp = response.readEntity(respType);
...
Run Code Online (Sandbox Code Playgroud)
泽西在最后一行抛出异常:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/octet-stream
Run Code Online (Sandbox Code Playgroud)
我做了一些调查.首先,我抓住了这个回应:
Content-Length: 93
Date: Thu, 21 Nov 2013 12:53:46 GMT
Server: APP
<root>
<returncode>XXX</returncode>
<desc>some description</desc>
</root>
Run Code Online (Sandbox Code Playgroud)
标头不包含有关MediaType的任何信息.
实际上,当我尝试调用response.getMediaType()时,它返回null.
我想,那就是问题所在.Jersey无法检测到响应的MediaType并默认设置它("application/octet-stream").但实际上我的回答是XML.有什么方法可以告诉泽西岛吗?
在“ 编写RESTful Web服务->生命周期和回调”部分:
因此,RESTful Web服务的生命周期是针对每个请求的,因此该服务不必担心并发性,并且可以安全地使用实例变量。
几行之后,他写道:
请记住,RESTful Web服务也可以使用@Stateless或@Singleton进行注释,以受益于会话bean的服务。
那是什么 每个请求的生命周期还是也可以是会话?
除此之外,如果生命周期是会话,则@Context在注入HttpHeaders属性时如何处理注释?标头在会话期间可能会有所不同,因此此属性是否总是在每次请求后更新?
抱歉我的英语不好.我正在使用灰熊和球衣来构建一个Web应用程序.
我这样实施
ErrorModel errorModel = new ErrorModel("1", "1", "1");
WebApplicationException applicationException = (WebApplicationException) exception;
return Response.status(applicationException.getResponse().getStatus()).type(MediaType.APPLICATION_JSON_TYPE).entity(errorModel).build();
Run Code Online (Sandbox Code Playgroud)
当我访问一个不存在的页面时.我发现它抛出一个WebApplicationException.所以我调试并发现正在调用此方法并返回上面的响应.但最后http响应是一个由grizzly构建的html页面.我该怎么办
我正在尝试按照本教程使用Java-ee实现REST服务器API .我使用Tomcat而不是Glassfish.
我可以开发一个servlet
@WebServlet(name = "hello", urlPatterns = "/")
public class HelloWorld extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("=)");
}
}
Run Code Online (Sandbox Code Playgroud)
并加入http:// localhost:9080 /我可以看到笑脸.但是当我尝试访问api路径时(http:// localhost:9080/api/recommended/all)我也得到了面子.如果我删除servlet类,我会收到404错误.我想我需要其他东西来自动构建api,但我不知道是什么.
有人能告诉我缺少什么吗?我该怎么办?
更新:在Intellij的Java Enterprise View中,我看到:
Web > HelloWorld
RESTful WS > recommend > all
Run Code Online (Sandbox Code Playgroud)
这些是我的api课程:
@ApplicationPath("/api")
public class REST_Config extends Application {
}
Run Code Online (Sandbox Code Playgroud)
而具体方法
@Path("recommend")
public class RecommenderController {
@Path("/all")
@GET
@Produces("application/json")
public JsonArray getAll(){
JsonArrayBuilder builder = Json.createArrayBuilder();
builder.add(Json.createObjectBuilder().add("1", "2.5"));
return …Run Code Online (Sandbox Code Playgroud) 服务器以JSON作为HTTP POST发送数据,我使用jax-rs来处理和检索数据.
我可以根据我的需要使用@Pathparam或@queryparam,但数据不喜欢其中任何一个.如果我是对的,也不在标题中,因为它们包含内容类型,日期和类似排序的内容.如何从POST检索数据?
@POST
@Path("/foo")
public void foo(){ //do i need to put sth in parameter paranthesis to get?
//handle the data!! but how??
}
Run Code Online (Sandbox Code Playgroud) jax-rs ×10
java ×7
jersey ×6
rest ×5
grizzly ×2
dropwizard ×1
file-upload ×1
glassfish ×1
http ×1
http-headers ×1
java-ee ×1
maven ×1
resteasy ×1
spring ×1
swagger ×1
tomcat ×1
tomcat5.5 ×1
web-services ×1