如何将名称值对作为正文传递给Jersey中的POST ReST服务.使用Apache Commons PostMethod类似于下面的代码
final PostMethod post = new PostMethod(url);
post.setRequestBody(new NameValuePair[] {
new NameValuePair("loginId", userId),
new NameValuePair("logonPassword", password),
new NameValuePair("signature", signature),
new NameValuePair("timestamp", timestamp),
new NameValuePair("sourceSiteId", sourceSiteId) });
Run Code Online (Sandbox Code Playgroud)
我正在将此调用移植到我的应用程序中.当前调用使用apache commons PostMethod.在我的应用程序中我使用泽西岛 所以我想使用jersey类/功能而不是apache.
我正在尝试配置一个ExceptionMapper,它将捕获我的应用程序中的所有404相关异常.这是我第一次尝试使用这个ExceptionMapper,因此面临很多问题,可能会遗漏一些愚蠢的东西:(
下面是我在ExceptionMapper类中所做的:
public class ClassNotFoundMapper implements ExceptionMapper<NotFoundException> {
@Override
public Response toResponse(NotFoundException ex) {
return Response.status(404).entity(ex.getMessage()).type("text/plain").build();
}
Run Code Online (Sandbox Code Playgroud)
}
在web.xml中我添加了这个条目:
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>
com.service.rest;
com.service.exception
</param-value>
</init-param>
Run Code Online (Sandbox Code Playgroud)
在服务中我这样做了:
@GET
@Path("{param}")
public Response getName(@PathParam("param") String msg, @HeaderParam("name") String headerName) {
//SOME CODE HERE AND THEN CONDITIONALLY RETURN THE EXCEPTION
return Response.status(Response.Status.NOT_FOUND).entity("NOT FOUND").build();
}
Run Code Online (Sandbox Code Playgroud)
不会调用ExceptionMapper中出现的异常.
请让我知道我错过了什么.
我想实现用一个简单的REST服务FIQL但我的代码抛出NullPointerException在哪里注入点SearchContext用@Context.这是我的代码
我的服务类:
import java.util.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.jaxrs.ext.search.SearchCondition;
import org.apache.cxf.jaxrs.ext.search.SearchContext;
@Path("/search")
public class Books {
private List<Book> theBooks = new LinkedList<Book>();
@Path("/book")
@GET
@Produces(MediaType.APPLICATION_XML)
public List<Book> getBook(@Context SearchContext searchContext) {
theBooks.add(new Book("1", "nick1"));
theBooks.add(new Book("2", "nick2"));
theBooks.add(new Book("3", "nick3"));
theBooks.add(new Book("4", "nick4"));
theBooks.add(new Book("5", "nick5"));
SearchCondition<Book> condition = searchContext
.getCondition(Book.class);
return condition.findAll(theBooks);
}
}
Run Code Online (Sandbox Code Playgroud)
我的书课
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Book {
private String …Run Code Online (Sandbox Code Playgroud) 我正在将我的项目从grails 2.2迁移到2.3,除了jaxrs插件之外,一切正常
我的BuildConfig.groovy看起来像:
...
grails.project.dependency.resolver = "maven"
grails.project.dependency.resolution = {
plugins {
compile ':jaxrs:0.8'
}
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息:
| Error Resolve error obtaining dependencies: The following artifacts could not be resolved: org.restlet.gae:org.restlet.ext.json:jar:2.0.0, org.restlet.gae:org.restlet:jar:2.0.0, org.restlet.gae:org.restlet.ext.servlet:jar:2.0.0: Could not find artifact org.restlet.gae:org.restlet.ext.json:jar:2.0.0 in grailsCentral (http://repo.grails.org/grails/plugins) (Use --stacktrace to see the full trace)
| Error Resolve error obtaining dependencies: The following artifacts could not be resolved: org.restlet.gae:org.restlet.ext.json:jar:2.0.0, org.restlet.gae:org.restlet:jar:2.0.0, org.restlet.gae:org.restlet.ext.servlet:jar:2.0.0: Could not find artifact org.restlet.gae:org.restlet.ext.json:jar:2.0.0 in grailsCentral (http://repo.grails.org/grails/plugins) (Use --stacktrace to see the full trace)
| …Run Code Online (Sandbox Code Playgroud) 当使用jersey 1.18尝试POST请求时,我得到以下异常:
Exception in thread "main" java.lang.AbstractMethodError: javax.ws.rs.core.Response.getStatusInfo()Ljavax/ws/rs/core/Response$StatusType;
at javax.ws.rs.WebApplicationException.computeExceptionMessage(WebApplicationException.java:205)
at javax.ws.rs.WebApplicationException.<init>(WebApplicationException.java:179)
at javax.ws.rs.WebApplicationException.<init>(WebApplicationException.java:244)
at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:159)
at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:300)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:217)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:153)
at com.sun.jersey.api.client.Client.handle(Client.java:652)
at com.sun.jersey.api.client.WebResource.voidHandle(WebResource.java:706)
at com.sun.jersey.api.client.WebResource.access$400(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:555)
at jtmt.shell.commands.upld.TrcUploader.upload(TrcUploader.java:29)
at jtmt.shell.commands.trcrt.ICMPTraceRoute.run(ICMPTraceRoute.java:92)
at jtmt.shell.commands.Main.<init>(Main.java:42)
at jtmt.shell.commands.Main.main(Main.java:64)
Run Code Online (Sandbox Code Playgroud)
产生这个的代码是:
Trace trc = Trace.fromTracerouteResult(trace);
WebResource wr = _c.resource(URL);
WebResource.Builder wrb = wr.cookie(new Cookie("user", USER));
wrb = wrb.cookie(new Cookie("auth", AUTH));
wrb.post(trc);
return true;
Run Code Online (Sandbox Code Playgroud)
entiry Trace看起来像这样:
@XmlRootElement
public class Trace {
private Map<Integer,List<String>> addressesPerHop;
private String source;
private String traget;
/* getters …Run Code Online (Sandbox Code Playgroud) 我正在使用ModelMApper将对象从DTO映射到Impl - 在反序列化对象时.这与JAxRS结合使用.当用户发出POST/PUT请求时,我不希望映射"id".
我需要跳过所有映射的"id"字段.我不想一个接一个地做这个,因为没有必要为所有类显式地图.如何配置映射器以跳过从所有DTO到Impls映射的所有"id"字段.
谢谢
我有一个Pojo对象,由Jersey使用jackson序列化:
public class BookOfFriendsAnswer {
private Map<String, List<BookSummary>> books;
public BookOfFriendsAnswer() {
}
public BookOfFriendsAnswer(Map<String, List<BookSummary>> books) {
this.books = books;
}
public Map<String, List<BookSummary>> getBooks() {
return books;
}
public void setBooks(Map<String, List<BookSummary>> books) {
this.books = books;
}
}
Run Code Online (Sandbox Code Playgroud)
序列化产生一个像这样的JSon:
{
"books": {
"entry": [
{
"key": "54567bbce4b0e0ef9379993e",
"value": "BookSummary{id='54567bbde4b0e0ef9379993f', title='title 1', authors=[Steve,James] } BookSummary{id='54567bd9e4b0e0ef93799940', title='Title 2', authors=[Simon, Austin]}"
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我试图从我的客户端反序列化消息时,如下所示:
mapper.readValue(json, clazz)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
无法识别的字段"key"(类com.example.server.api.BookSummary),未标记为可忽略
我不知道问题是来自服务器生成的JSOn还是客户端的反序列化.
你知道什么是问题以及如何纠正它?
非常感谢
我的功能看起来像这样:
@PUT
@Path("property/{uuid}/{key}/{value}")
@Produces("application/xml")
public Map<String,ValueEntity> updateProperty(@Context HttpServletRequest request,
@PathParam("key") String key,
@PathParam("value") String value,
@PathParam("uuid") String uuid) throws Exception {
...
}
Run Code Online (Sandbox Code Playgroud)
我必须修改它,因此它接受来自REST调用的无限(或许多)键值对列表,例如
@Path("property/{uuid}/{key1}/{value1}/{key2}/{value2}/{key3}/{value3}/...")
Run Code Online (Sandbox Code Playgroud)
是否可以将它们存储在数组或列表中,所以我没有列出几十个@PathParams和参数,以避免这种情况:
@PathParam("key1") String key1,
@PathParam("key2") String key2,
@PathParam("key3") String key3,
Run Code Online (Sandbox Code Playgroud) 我开始学习用于开发宁静网络服务的球衣.
正如我在大多数示例中注意到的那样使用以下注释:
@Consumes
Run Code Online (Sandbox Code Playgroud)
定义输入参数的格式
@Produces
Run Code Online (Sandbox Code Playgroud)
定义输出参数的格式
但在实际代码中,我看到的方法如下所示:
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/login")
public Response login(@FormParam("login") final String username, @FormParam("password") final String password){...}
Run Code Online (Sandbox Code Playgroud)
我看到这个方法使用POSTHTTP方法.参数userName和password将具有形式 @Consumes(MediaType.APPLICATION_FORM_URLENCODED).我看到URL来执行这个方法.
但是我不明白这个方法会返回什么.哪种格式?
我遇到麻烦(联合国)将java.util.Date对象编组到时间戳中.理想情况下,时间戳应采用UTC-0格式,而不是服务器的本地时区.虽然如果需要,我可以很容易地解决这个问题.
注意:我知道这里有几个关于堆栈溢出的类似主题,但是我遇到的每个人都要么过时(关于正在使用的API),要么与将Date对象序列化为字符串有关.
以下是我的POM文件的摘录:
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.15</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
样本模型类:
public class PersonJSON {
private Date birthDate;
}
Run Code Online (Sandbox Code Playgroud)
预期产出(假设出生日期为2015年2月1日00:00:00 UTC-0):
{"birthDate":1422748800000}
Run Code Online (Sandbox Code Playgroud)
当前输出:
{"birthDate":"2015-02-01"}
Run Code Online (Sandbox Code Playgroud)
是否可以解决这个问题(理想情况下使用注释)?
解
事实证明,错误是由Java.sql.Date到Java.util.Date的隐式转换引起的.转换不会抛出任何异常,并且sql.Date扩展了util.Date,因此逻辑上它应该可以工作,但事实并非如此.解决方案是从Java.sql.Date中提取时间戳,并将其用作Java.util.Date构造函数的输入.
如果您确实想要更改格式,假设您有一个有效的Java.util.Date对象,那么peeskillet列出的方法是正确的.
jax-rs ×10
java ×7
jersey ×5
rest ×4
jackson ×2
json ×2
cxf ×1
grails-2.2 ×1
grails-2.3 ×1
jaxb ×1
maven ×1
modelmapper ×1
name-value ×1
servlets ×1
web-services ×1