帮忙用Java写一份Android retrofit代码
时间: 2024-06-10 12:04:01 浏览: 186
好的,我会帮您用Java写一份Android retrofit代码。以下是代码示例:
```java
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;
public class RetrofitExample {
private static final String BASE_URL = "https://api.github.com/";
public static void main(String[] args) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
Call<User> call = service.getUser("octocat");
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
System.out.println(user.getLogin());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
t.printStackTrace();
}
});
}
interface GitHubService {
@GET("users/{user}")
Call<User> getUser(@Path("user") String user);
}
public static class User {
private String login;
public String getLogin() {
return login;
}
}
}
```
这是一个简单的 Retrofit 示例,包括创建 Retrofit 实例,定义接口和异步调用示例。您可以根据自己的需要进行修改和扩展。希望对您有所帮助!
阅读全文