在我的android应用程序中,我正在使用rest模板进行服务调用,但问题是当任何服务被调用时,我将遇到错误。服务未连接到服务器。
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.lss.company, PID: 8611
java.lang.NoClassDefFoundError: org.springframework.web.util.UriTemplate
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:498)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:447)
at com.lss.company.services.ServerAuthenticateService.getAllEmployeeList(ServerAuthenticateService.java:7320)
at com.lss.company.view.LoginActivity.onCreate(LoginActivity.java:138)
at android.app.Activity.performCreate(Activity.java:5459)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2458)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5598)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
下面是build.gradle依赖代码
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
applicationId "com.lss.company"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
multiDexEnabled true
}
lintOptions {
checkReleaseBuilds false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
debuggable true
}
}
dexOptions {
javaMaxHeapSize "4g"
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:26.0.0'
compile 'com.android.support:design:26.0.0'
compile 'com.android.support:cardview-v7:26.0.0'
compile 'com.android.support:recyclerview-v7:26.0.0'
compile 'org.springframework.android:spring-android-rest-template:2.0.0.M3'
compile 'org.springframework.android:spring-android-core:2.0.0.M3'
compile 'joda-time:joda-time:2.3'
compile 'com.fasterxml.jackson.core:jackson-databind:2.9.0'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
compile 'com.fasterxml.jackson.core:jackson-core:2.9.0'
compile 'com.google.code.gson:gson:2.8.1'
compile 'com.android.support:multidex:1.0.1'
compile 'net.sourceforge.jexcelapi:jxl:2.6.12'
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.github.ganfra:material-spinner:2.0.0'
compile 'com.github.wseemann:FFmpegMediaMetadataRetriever:1.0.14'
compile 'commons-io:commons-io:1.3.2'
compile 'de.hdodenhof:circleimageview:2.2.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
testCompile 'junit:junit:4.12'
}
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '26.1.0'
}
}
}
}
到现在为止没有错误,并且我所有的服务都可以正常工作,但是突然出现了这个错误,不允许我继续操作。下面是对服务器的调用。
public List<Employee> getAllEmployeeList() {
String plainClientCredentials="************************";
String base64ClientCredentials = new String(Base64.encode(plainClientCredentials.getBytes(),Base64.NO_WRAP));
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64ClientCredentials);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<String> restRes = restTemplate.exchange(LoginActivity.strMainUrl+"protected/users/getAllEmployeeList", HttpMethod.GET, entity, String.class);
System.out.println("restRes : "+restRes);
if (restRes.getStatusCode() == HttpStatus.OK) {
AppBackupCache.checkToken = 200;
String resBody = restRes.getBody();
Type listType = new TypeToken<List<Employee>>() {}.getType();
List<Employee> employeeList = new ArrayList<Employee>();
schoolList = gson.fromJson(resBody,listType);
return employeeList;
} else if(restRes.getStatusCode() == HttpStatus.UNAUTHORIZED) {
AppBackupCache.checkToken = 401;
return null;
} else {
AppBackupCache.checkToken = 402;
return null;
}
}
以上代码到目前为止运行良好,并且突然出现错误并且该错误不起作用,在每个服务调用中都发生相同的情况。我的代码有什么问题。 下面是我从活动类调用其他服务的方式。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginpage);
this.progressdialog = new ProgressDialog(this);
this.progressdialog.setMessage("Please Wait....");
this.progressdialog.setCancelable(false);
this.accountManager = AccountManager.get(getBaseContext());
String accountName = getIntent().getStringExtra(ARG_ACCOUNT_NAME);
this.authTokenType = getIntent().getStringExtra(ARG_AUTH_TYPE);
this.edtUserName = (EditText) findViewById(R.id.edtUserName);
this.edtPassword = (EditText) findViewById(R.id.edtPassword);
this.edtEmail = (EditText) findViewById(R.id.edtEmail);
this.btnNext = (Button) findViewById(R.id.btnNext);
this.btnBack = (Button) findViewById(R.id.btnBack);
this.linLayMain = (LinearLayout) findViewById(R.id.linLayMain);
this.acTxtCompany = (AutoCompleteTextView) findViewById(R.id.acTxtCompany );
if (this.authTokenType != null) {
this.authTokenType = AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS;
}
if (accountName != null) {
this.edtUserName.setText(accountName);
} else {
String lastUser = getSharedPreferences("version", 0).getString("userName", null);
if (lastUser != null) {
this.edtUserName.setText(lastUser);
} else if (this.accountManager.getAccountsByType("com.lss.company").length > 0) {
this.edtUserName.setText(this.accountManager.getAccountsByType("com.lss.company")[0].name);
}
}
this.submit = (Button) findViewById(R.id.submit);
this.submit.setOnClickListener(new C12411());
if (AppBackupCache.isServerReachable(getApplicationContext())) {
this.employeeList = serverAuthenticateService.getAllEmployeeList();
if (AppBackupCache.checkToken == ItemTouchHelper.Callback.DEFAULT_DRAG_ANIMATION_DURATION) {
showDepartmentSpinner();
} else if (AppBackupCache.checkToken == 401) {
this.manager.invalidateAuthToken("com.lss.company", this.authtoken);
this.authtoken = null;
final AccountManagerFuture<Bundle> future = this.manager.getAuthToken(this.mAccount, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS, true, null, null);
new Thread(new Runnable() {
public void run() {
try {
Bundle bnd = (Bundle) future.getResult();
LoginActivity.this.authtoken = bnd.getString("authtoken");
if (LoginActivity.this.authtoken != null) {
LoginActivity.this.employeeList = serverAuthenticateService.getAllEmployeeList();
if (AppBackupCache.checkToken == ItemTouchHelper.Callback.DEFAULT_DRAG_ANIMATION_DURATION) {
LoginActivity.this.showDepartmentSpinner();
return;
}
LoginActivity.this.getMsgBox("Error", "Something went wrong");
return;
}
System.out.println("************** NULL *****************");
LoginActivity.this.getMsgBox("", "Token not refreshed....");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
AppBackupCache.checkToken = 401;
return;
}
getMsgBox("No connection", "No connection");
}
服务类别:
public class ServerAuthenticateService implements ServerAuthenticate {
String authAToken = null;
Gson gson;
RestTemplate restTemplate;
public List<Departments> getAllDepartmentList() {
MultiValueMap headers = new HttpHeaders();
System.out.println("authToken " + authToken);
headers.set(HttpHeaders.AUTHORIZATION, "bearer " + authToken);
ResponseEntity<String> restRes = this.restTemplate.exchange(companyUrl + "protected/users/getAllDepartmentList", HttpMethod.POST, new HttpEntity(headers), String.class, new Object[0]);
if (restRes.getStatusCode() == HttpStatus.OK) {
AppBackupCache.checkToken = Callback.DEFAULT_DRAG_ANIMATION_DURATION;
String resBody = (String) restRes.getBody();
Type listType = new C07736().getType();
List<Departments> catList = new ArrayList();
return (List) this.gson.fromJson(resBody, listType);
} else if (restRes.getStatusCode() == HttpStatus.UNAUTHORIZED) {
AppBackupCache.checkToken = 401;
return null;
} else {
AppBackupCache.checkToken = 402;
return null;
}
}
public ServerAuthenticateService() {
try {
restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
protected boolean hasError(HttpStatus statusCode) {
return false;
}
});
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement json, Type type, JsonDeserializationContext deserializationContext) throws JsonParseException {
String frStr = json.getAsJsonPrimitive().getAsString();
Date retDate =null;
try {
retDate = dtfDate.parse(frStr);
} catch (ParseException e) {
e.printStackTrace();
}
return retDate;
}
});
builder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
String jsDate = dtf.format(src);
return new JsonPrimitive(jsDate);
}
});
builder.registerTypeAdapter(Timestamp.class, new JsonDeserializer<Timestamp>() {
@Override
public Timestamp deserialize(JsonElement json, Type type, JsonDeserializationContext deserializationContext) throws JsonParseException {
String strDate = json.getAsJsonPrimitive().getAsString();
Date date = null;
try {
date = dtf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return new Timestamp(date.getTime());
}
});
builder.registerTypeAdapter(byte[].class, new JsonDeserializer<byte[]>() {
@Override
public byte[] deserialize(JsonElement json, Type type, JsonDeserializationContext deserializationContext) throws JsonParseException {
return Base64.decode(json.getAsString(), Base64.NO_WRAP);
}
});
gson = builder.create();
} catch (Exception e) {
e.printStackTrace();
}
}
}
当我在名为AttachmentActivity的活动上注释了oncreate代码时,loginActivity上的错误消失了。该错误显示在LoginActivity上,因为从那里开始第一个Web服务调用,如果我注释了此行this.employeeList = serverAuthenticateService.getAllEmployeeList();
,则该错误可能出现在下一个活动的下一个网络服务调用中。
onCreate()
上的AttachmentActivity
:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.attachment_activity);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setSubtitle((CharSequence) "Add staff");
this.userId = getIntent().getExtras().getLong("userId");
this.companyId = getIntent().getExtras().getInt("companyId");
this.companyUrl = getIntent().getExtras().getString("companyUrl");
this.screen = getIntent().getExtras().getInt("screen");
this.manager = AccountManager.get(getApplicationContext());
this.sharedPreferences = getSharedPreferences("version", 0);
this.accNow = this.sharedPreferences.getInt("AccountNow", 0);
this.childNow = this.sharedPreferences.getInt("ChildNow", 0);
this.mAccount = this.manager.getAccountsByType("com.lss.company")[this.accNow];
this.authtoken = this.manager.peekAuthToken(this.mAccount, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS);
this.fontFamily = Typeface.createFromAsset(getAssets(), "fonts/fontawesome-webfont.ttf");
this.edtSelDept = (EditText) findViewById(R.id.edtSelDept);
this.edtDescription = (EditText) findViewById(R.id.edtDescription);
this.edtLink = (EditText) findViewById(R.id.edtLink);
this.cardVwKeyPair = (CardView) findViewById(R.id.cardVwKeyPair);
this.cardVwDocuments = (CardView) findViewById(R.id.cardVwDocuments);
this.cardVwMedia = (CardView) findViewById(R.id.cardVwMedia);
this.mSpnCategory = (MaterialSpinner) findViewById(R.id.mSpnCategory);
this.frameLayout = (FrameLayout) findViewById(R.id.frame_layout);
this.fabMenu = (FloatingActionsMenu) findViewById(R.id.fab_menu);
this.fabAdd = (FloatingActionButton) findViewById(R.id.fabAdd);
this.rcyAttachment = (RecyclerView) findViewById(R.id.rcyAttachment);
this.rcyHorDocuments = (RecyclerView) findViewById(R.id.rcyHorDocuments);
this.rcyMedia = (RecyclerView) findViewById(R.id.rcyMedia);
this.mSpnType = (MaterialSpinner) findViewById(R.id.mSpnType);
this.txtIpSelDept = (TextInputLayout) findViewById(R.id.txtIpSelDept);
this.txtIpDescription = (TextInputLayout) findViewById(R.id.txtIpDescription);
this.txtIpLink = (TextInputLayout) findViewById(R.id.txtIpLink);
this.cardVwStaff = (CardView) findViewById(R.id.cardVwStaff);
this.acTxtStaffId = (AutoCompleteTextView) findViewById(R.id.acTxtStaffId);
this.btnAdd = (Button) findViewById(R.id.btnAdd);
this.lvStaff = (ListView) findViewById(R.id.lvStaff);
this.fabMenu.setVisibility(0);
this.frameLayout.getBackground().setAlpha(0);
fabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
@Override
public void onMenuExpanded() {
frameLayout.getBackground().setAlpha(200);
frameLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
fabMenu.collapse();
return true;
}
});
}
@Override
public void onMenuCollapsed() {
frameLayout.getBackground().setAlpha(0);
frameLayout.setOnTouchListener(null);
}
});
this.mLayoutManager1 = new LinearLayoutManager(this);
this.rcyAttachment.setLayoutManager(this.mLayoutManager1);
if (getResources().getConfiguration().orientation == 1) {
this.rcyAttachment.setLayoutManager(new GridLayoutManager(this, 3));
} else {
this.rcyAttachment.setLayoutManager(new GridLayoutManager(this, 3));
}
this.rcyMedia.setLayoutManager(new LinearLayoutManager(this, 1, false));
this.rcyMedia.setItemAnimator(new DefaultItemAnimator());
this.progressdialog = new ProgressDialog(this);
this.progressdialog.setMessage("Please Wait....");
this.progressdialog.setCancelable(false);
this.fabAdd.setOnClickListener(new C09662());
this.fabAdd.setVisibility(0);
this.cardVwKeyPair.setVisibility(0);
this.mSpnCategory.setVisibility(0);
this.mSpnType.setVisibility(0);
this.txtIpDescription.setVisibility(0);
this.txtIpLink.setVisibility(0);
this.categoryList = AppBackupCache.getCategoryList();
if (this.screen == 1) {
this.txtIpSelDept.setVisibility(0);
getStaffDeptAndTypes();
setupCategorySpinner();
} else if (this.screen == 2) {
this.cardVwStaff.setVisibility(0);
getAllStaffAndTypes();
setupCategorySpinner();
}
this.edtSelDept.setOnClickListener(new C09673());
this.btnAdd.setOnClickListener(new C09684());
}
答案 0 :(得分:0)
您已经错过了在类路径中包含spring-web的问题。将其添加到您的Gradle文件中,它应该可以工作。
compile "org.springframework:spring-web:<!--your spring version-->"