下面是我到目前为止所学的示例代码 -具有流媒体功能的接口和客户端-服务器流媒体示例。
我还没有向界面添加参数,它只是下载 - 还没有上传。
界面:
public interface DownloadResource {
public ReadableRepresentation download();
}
与协议的接口:(逻辑与技术分离):
public interface DownloadResourceProtocol extends DownloadResource {
@Get
@Override
public ReadableRepresentation download();
}
客户:
ClientResource cr = new ClientResource("http://10.0.2.2:8888/download/");
cr.setRequestEntityBuffering(true);
DownloadResource downloadResource = cr.wrap(DownloadResourceProtocol.class);
// Remote invocation - seamless:
Representation representation = downloadResource.download();
// Using data:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
IOUtils.copy(representation.getStream(), byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
Log.i("Byte array: " + Arrays.toString(byteArray));
服务器:
public class DownloadResourceImpl extends ServerResource implements DownloadResourceProtocol {
@Override
public ReadableRepresentation download() {
InputStreamChannel inputStreamChannel;
try {
inputStreamChannel = new InputStreamChannel(new ByteArrayInputStream(new byte[]{1,2,3,4,5,6,7,8,9,10}));
return new ReadableRepresentation(inputStreamChannel, MediaType.ALL);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
配置:
public class SampleApplication extends Application {
@Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach("/download/", DownloadResourceImpl.class);
return router;
}
}