我尝试创建自定义http连接很多次,但现在我使用libruary retrofit
来表示multipart / form-data。我有错误:
java.lang.NoClassDefFoundError: com.squareup.okhttp.OkHttpClient
at retrofit.client.OkClient.generateDefaultOkHttp(OkClient.java:35)
at retrofit.client.OkClient.<init>(OkClient.java:44)
at service.ServiceGenerator.createService(ServiceGenerator.java:14)
at profile.Optional.onActivityResult(Optional.java:555)
at android.app.Activity.dispatchActivityResult(Activity.java:4663)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3131)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3178)
at android.app.ActivityThread.access$1100(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4624)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
在profile.Optional.onActivityResult(Option.java:555)其行:
UploadPhotoRetroService service = ServiceGenerator.createService(UploadPhotoRetroService.class, "https://example.net");
这是我的代码:
Optional.class
UploadPhotoRetroService service = ServiceGenerator.createService(UploadPhotoRetroService.class, "https://rest.senseloopcore.no/users/image");
TypedFile typedFile = new TypedFile("image/jpeg", fileName);
service.upload(typedFile, new Callback<String>() {
@Override
public void success(String result, Response response) {
Log.e("result", result);
}
@Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
ServiceGenerator.class
public class ServiceGenerator {
private ServiceGenerator() {
}
public static <S> S createService(Class<S> serviceClass, String baseUrl) {
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(baseUrl)
.setClient(new OkClient());
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
}
UploadPhotoRetroService
public interface UploadPhotoRetroService {
@Headers({
"id: 123",
"key: 222"
})
@Multipart
@POST("/upload")
void upload(@Part("Photo") TypedFile file, Callback<String> callback);
}
答案 0 :(得分:0)
如果您使用的是gradle和android studio,请确保在build.gradle文件中编译'com.squareup.okhttp:okhttp:2.2.0'