0
我一直在編寫RESTful Web服務。MessageBodyWriter在澤西島的自定義媒體類型
- Glassfish的3(基於Java 6)
- JDK V7
- Eclipse的EE開普勒
- 澤西(Glassfish的部分)
我創建:我使用的技術定製POJO定製媒體類型:
public final class SimpleEntity{
private int value = 0;
private String stValue = "";
public SimpleEntity(){}
public SimpleEntity(int value, String stValue) {
super();
this.value = value;
this.stValue = stValue;
}
... getters, setters
我的資源m ethod:
@POST
@Produces("application/entity")
@Path("/getSimpleEntityNeedsProvider")
public Response getSimpleEntityNeedsProvider(){
SimpleEntity entity = new SimpleEntity(47, "String input value");
return Response.ok().entity(entity).build();
}
我的消息主體作家:
@Provider
@Produces("application/entity")
public final class SimpleEntityBodyWriterProvider implements MessageBodyWriter<SimpleEntity>{
private static Logger log = Logger.getLogger(Class.class);
@Override
public long getSize(SimpleEntity arg0, Class arg1, Type arg2, Annotation[] arg3,
MediaType arg4) {
return -1;
}
@Override
public boolean isWriteable(Class arg0, Type arg1, Annotation[] arg2,
MediaType arg3) {
if(arg0.equals(SimpleEntity.class)){
return true;
}
return false;
}
@Override
public void writeTo(SimpleEntity entity, Class arg1, Type arg2, Annotation[] arg3,
MediaType media, MultivaluedMap arg5, OutputStream out)
throws IOException, WebApplicationException {
log.log(Level.INFO, "Input to SimpleEntityBodyWriterProvider: "+entity.getValue());
out.write(entity.getValue());
out.write(entity.getStValue().getBytes());
}
}
我的服務客戶端:
private void getSimpleEntityNeedsProvider(String strUrl, String method){
HttpURLConnection connect = null;
try {
URL url = new URL(strUrl);
connect = (HttpURLConnection)url.openConnection();
connect.setRequestProperty("Accept", "application/entity");// Accept from server
connect.setRequestMethod(method);
connect.connect();
InputStream input = connect.getInputStream();
int size = input.available();
byte[] b = new byte[size];
input.read(b, 0, size);
System.out.println("From resource: "+new String(b));
System.out.println("Status: "+connect.getResponseCode()+" : "+connect.getResponseMessage());
}
catch(IOException e){
e.printStackTrace();
}
}
根路徑:
@ApplicationPath("/rest/v6")
public class AppV6 extends Application {
private static Logger log = Logger.getLogger(Class.class.getName());
public AppV6(){}
@Override
public Set<Class<?>> getClasses(){
Set<Class<?>> cls = new HashSet<>();
cls.add(SimpleEntity.class);
cls.add(SimpleEntityBodyWriterProvider.class);
return cls;
}
}
當我運行從我的服務客戶端的應用程序,我得到以下輸出:
From resource: /String input value
Status: 200 : OK
我想,纔能有更好的理解基於REST /澤西服務的使用自定義介質類型和MessageBodyWriter
。 我有的問題:
- 這是涉及/編碼自定義媒體類型的正確方法嗎?
- 我在服務客戶端收到的數據不完全正確。也就是說,而不是「/」這個值需要是一個數字47.所以,爲什麼我得到一個字符而不是數字?
- 正如您在資源方法中看到的,我向定製POJO輸入了兩個值:數字和字符串。在服務客戶端,我有
InputStream
。我得到整體數據的字節數組。我怎樣才能讀取數據作爲單獨的數據塊,在我的POJO中編碼爲字段?我可以逐字節讀取,但這是否正確?