我尝试使用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()));
但是,此代码无效,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 org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:634)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:631)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:631)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:391)
at org.glassfish.jersey.client.JerseyInvocation$Builder.put(JerseyInvocation.java:285)
at com.clouddrive.dropbox.DropBoxController.uploadFile(DropBoxController.java:161)
at com.clouddrive.util.WatchDir.processEvents(WatchDir.java:200)
at com.clouddrive.CloudDrive.main(CloudDrive.java:111)
... 6 more
答案 0 :(得分:11)
我修改了初始化代码并确认代码正常工作。
Client client = ClientBuilder.newBuilder()
.register(MultiPartFeature.class)
.build();
对于给您带来的不便,我深表歉意。