我有一个用于令牌登录的Web服务链接。但在这个链接中,没有" /"在链接的末尾。并且android studio会出现名为baseUrl must end in /
的错误。当我提出/
时,它不会获得令牌并说token is not truth :(
,因为我的想法中的链接不正确。我使用retrofit2
库。请帮我解决一下。
MainActivity.java
public class MainActivity extends AppCompatActivity {
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://website.net/token")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
UserClient userClient = retrofit.create(UserClient.class);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button loginButton=(Button)findViewById(R.id.btn_login);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
login();
/* Intent intentLogin=new Intent(MainActivity.this,MainPageActivity.class);
startActivity(intentLogin);*/
}
});
}
private static String token;
private void login() {
Login login = new Login("abcd", "1234");
Call<User> call = userClient.login(login);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()){
Toast.makeText(MainActivity.this, response.body().getToken(), Toast.LENGTH_SHORT).show();
token = response.body().getToken();
}
else {
Toast.makeText(MainActivity.this, "Token is not truth :(", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(MainActivity.this, "error!", Toast.LENGTH_SHORT).show();
}
});
}
}
`Login.java
public class Login {
private String user;
private String password;
public Login(String user, String password) {
this.user = user;
this.password = password;
}
}
User.java
public class User {
private int id;
private String email;
private String token;
public int getId(){
return id;
}
public void setId(){
this.id = id;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getToken(){return token;}
public void setToken(String token){this.token = token;}
}
UserClient.java
import com.squareup.okhttp.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
public interface UserClient {
@POST("Login")
Call<User> login(@Body Login login);
// @GET("secretinfo")
// Call<ResponseBody> getSecret(@Header("Authorization") String authToken);
}
答案 0 :(得分:2)
在
中使用到此为止Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://website.net/")
.addConverterFactory(GsonConverterFactory.create());
并在UserClient接口类
中public interface UserClient {
@POST("token") Call<User> login(@Body Login login);
}