我有一个Android应用程序,有3个活动:
我必须使用REST Apis。到目前为止,我所做的研究指导我使用Retrofit。我检查了如何使用它并发现:
如果我的应用程序是一个单独的活动应用程序,我会在我的MainActivity.java中处理所有内容,但我不知道如何以及在何处将步骤1,2,3中的所有代码用于我的3个活动中。你能告诉我如何在我的应用程序中使用Retrofit吗?非常感谢。
具体来说,我需要网络电话: 1.登录用户 2.获取用户的所有任务。 对于两者,我将使用给定的REST api。
*********************************************
Calling Api USing Retrofit
*********************************************
**Dependancies** :-
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.android.support:cardview-v7:27.1.1'
enter code here
**Model**
use the Pozo class
**Api Call**
-> getLogin() // use the method
//API call for Login
private void getLogin()
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("email_id", edit_email.getText().toString());
requestParams.put("password", edit_password.getText().toString());
Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
ShowProgress();
}
@Override
public void onFinish() {
super.onFinish();
Hideprogress();
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("", "Login RESPONSE-" + response);
Login login = new Gson().fromJson(String.valueOf(response), Login.class);
edit_email.setText("");
edit_password.setText("");
if (login.getStatus().equals("true")) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
mdToast.show();
Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
hideKeyboard(SignInActivity.this);
Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("", throwable.getMessage());
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
});
}
答案 0 :(得分:96)
使用Retrofit非常简单明了。
首先,您需要为项目添加改造,例如使用Gradle构建系统。
compile 'com.squareup.retrofit:retrofit:1.7.1' |
另一种方法是你可以下载.jar并将它放到你的libs文件夹中。
然后,您需要定义将由Retrofit用于对REST端点进行API调用的接口。例如,对于用户:
public interface YourUsersApi {
//You can use rx.java for sophisticated composition of requests
@GET("/users/{user}")
public Observable<SomeUserModel> fetchUser(@Path("user") String user);
//or you can just get your model if you use json api
@GET("/users/{user}")
public SomeUserModel fetchUser(@Path("user") String user);
//or if there are some special cases you can process your response manually
@GET("/users/{user}")
public Response fetchUser(@Path("user") String user);
}
确定。现在您已经定义了API接口,您可以尝试使用它。
首先,您需要创建 RestAdapter 的实例,并设置API后端的基本网址。它也很简单:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://yourserveraddress.com")
.build();
YourUsersApi yourUsersApi = restAdapter.create(YourUsersApi.class);
此处Retrofit将从界面读取您的信息,并根据您提供的实际将执行HTTP请求的元信息创建 RestHandler 。
然后在幕后,一旦收到响应,在json api的情况下,您的数据将使用Gson库转换为您的模型,因此您应该意识到Gson中存在的限制实际上存在于Retrofit中。
要扩展/覆盖序列化程序/反序列化您的响应数据到您的模型的过程,您可能希望提供自定义序列化程序/解串器进行改造。
在这里,您需要实现Converter接口并实现2种方法 fromBody() 和 toBody() 。
以下是示例:
public class SomeCustomRetrofitConverter implements Converter {
private GsonBuilder gb;
public SomeCustomRetrofitConverter() {
gb = new GsonBuilder();
//register your cursom custom type serialisers/deserialisers if needed
gb.registerTypeAdapter(SomeCutsomType.class, new SomeCutsomTypeDeserializer());
}
public static final String ENCODING = "UTF-8";
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
String charset = "UTF-8";
if (body.mimeType() != null) {
charset = MimeUtil.parseCharset(body.mimeType());
}
InputStreamReader isr = null;
try {
isr = new InputStreamReader(body.in(), charset);
Gson gson = gb.create();
return gson.fromJson(isr, type);
} catch (IOException e) {
throw new ConversionException(e);
} catch (JsonParseException e) {
throw new ConversionException(e);
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException ignored) {
}
}
}
}
@Override
public TypedOutput toBody(Object object) {
try {
Gson gson = gb.create();
return new JsonTypedOutput(gson.toJson(object).getBytes(ENCODING), ENCODING);
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
private static class JsonTypedOutput implements TypedOutput {
private final byte[] jsonBytes;
private final String mimeType;
JsonTypedOutput(byte[] jsonBytes, String encode) {
this.jsonBytes = jsonBytes;
this.mimeType = "application/json; charset=" + encode;
}
@Override
public String fileName() {
return null;
}
@Override
public String mimeType() {
return mimeType;
}
@Override
public long length() {
return jsonBytes.length;
}
@Override
public void writeTo(OutputStream out) throws IOException {
out.write(jsonBytes);
}
}
}
现在,您需要在构建RestAdapter时使用 setConverter() 来启用自定义适配器
确定。现在您知道如何将数据从服务器提供到Android应用程序。但是你需要以某种方式管理你的数据并在正确的位置调用REST调用。 在那里我建议使用android Service或AsyncTask或loader或rx.java来查询后台线程上的数据,以便不阻止你的UI。
所以现在你可以找到最适合的地方
SomeUserModel yourUser = yourUsersApi.fetchUser("someUsers")
获取远程数据。
答案 1 :(得分:24)
我刚刚使用了改装几周,起初我发现在我的应用程序中很难使用。我想与您分享在您的应用程序中使用改造的最简单方法。如果你已经很好地掌握了改造,那么稍后你就可以增强你的代码(将你的ui与api分开并使用回调),也可以从上面的帖子中获得一些技巧。
在您的应用中,您有登录,活动列表任务和活动以查看详细任务。
首先,你需要在你的应用程序中添加改装,并且有两种方式,请点击上面的@artemis帖子。
Retrofit使用interface作为您的API。所以,创建一个接口类。
public interface MyApi{
/*LOGIN*/
@GET("/api_reciever/login") //your login function in your api
public void login(@Query("username") String username,@Query("password") String password,Callback<String> calback); //this is for your login, and you can used String as response or you can use a POJO, retrofit is very rubust to convert JSON to POJO
/*GET LIST*/
@GET("/api_reciever/getlist") //a function in your api to get all the list
public void getTaskList(@Query("user_uuid") String user_uuid,Callback<ArrayList<Task>> callback); //this is an example of response POJO - make sure your variable name is the same with your json tagging
/*GET LIST*/
@GET("/api_reciever/getlistdetails") //a function in your api to get all the list
public void getTaskDetail(@Query("task_uuid") String task_uuid,Callback<Task> callback); //this is an example of response POJO - make sure your variable name is the same with your json tagging
}
创建另一个接口类来保存api的所有BASE ADDRESS
public interface Constants{
public String URL = "www.yoururl.com"
}
在您的登录活动中,创建一个处理改造的方法
private void myLogin(String username,String password){
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Constants.URL) //call your base url
.build();
MyApi mylogin = restAdapter.create(MyApi.class); //this is how retrofit create your api
mylogin.login(username,password,new Callback<String>() {
@Override
public void success(String s, Response response) {
//process your response if login successfull you can call Intent and launch your main activity
}
@Override
public void failure(RetrofitError retrofitError) {
retrofitError.printStackTrace(); //to see if you have errors
}
});
}
在您的MainActivityList
中private void myList(String user_uuid){
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Constants.URL) //call your base url
.build();
MyApi mytask = restAdapter.create(MyApi.class); //this is how retrofit create your api
mytask.getTaskDetail(user_uuid,new Callback<Task>>() {
@Override
public void success(ArrayList<Task> list, Response response) {
//process your response if successful load the list in your listview adapter
}
@Override
public void failure(RetrofitError retrofitError) {
retrofitError.printStackTrace(); //to see if you have errors
}
});
}
在您的详细清单
中private void myDetailed(String task_uuid){
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Constants.URL) //call your base url
.build();
MyApi mytask = restAdapter.create(MyApi.class); //this is how retrofit create your api
mytask.getTaskList(task_uuid,new Callback<Task>() {
@Override
public void success(Task task, Response response) {
//process your response if successful do what you want in your task
}
@Override
public void failure(RetrofitError retrofitError) {
retrofitError.printStackTrace(); //to see if you have errors
}
});
}
希望这会对你有所帮助,尽管它真的是最简单的改装方式。
答案 2 :(得分:4)
看看这个优秀的博客,关于将Retrofit与Otto结合使用,两个图书馆均来自Square。
http://www.mdswanson.com/blog/2014/04/07/durable-android-rest-clients.html
基本思想是您将在Application类中保存对“repository”对象的引用。该对象将具有“订阅”以休息api事件请求的方法。收到一个后,它将进行正确的Retrofit调用,然后“发布”响应,然后可以由另一个组件(例如发出请求的活动)“订阅”。
正确完成所有设置后,通过rest api访问数据变得非常简单。例如,对数据的请求看起来像这样:
mBus.post(new GetMicropostsRequest(mUserId));
并且使用数据看起来像这样:
@Subscribe
public void onGetUserProfileResponse(GetUserProfileResponse event) {
mView.setUserIcon("http://www.gravatar.com/avatar/" + event.getGravatar_id());
mView.setUserName(event.getName());
}
这需要一些前期努力,但最终通过Rest从后端访问您需要的任何内容变得“微不足道”。
答案 3 :(得分:3)
使用RetroFit非常简单。
在build.gradle中添加dependecy。
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
为所有http方法创建一个接口。
复制你的json输出并创建pojo类来接收你的json 回复,你可以从JsonSchema2pojo 网站制作pojo。
制作适配器并调用您的方法
完整演示试用本教程Retrofit Android example
答案 4 :(得分:3)
您可以尝试在应用程序类中保存对api的引用。然后你可以从任何活动或片段中获取它的实例并从那里获得api。这听起来有点奇怪,但它可能是一个简单的DI替代品。如果你只在你的应用程序类中存储引用,它就不会成为一种上帝对象
UPD:http://square.github.io/retrofit/ - 这里有一些文档,可能很有用
答案 5 :(得分:2)
我发现这些教程AndroidHive,CodePath有用
我将简要介绍一下我所学到的知识。
第1步:添加这三个dependencies to build.gradle
并将Internet permission
添加到Manifest
compile 'com.google.code.gson:gson:2.6.2' // for string to class conversion. Not Compulsory
compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory
compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion
在Manifest中添加它们
<uses-permission android:name="android.permission.INTERNET" />
第2步 Creae ApiClient和ApiInterface。
public class ApiClient {
public static final String BASE_URL = "http://yourwebsite/services/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
其中ApiInterface.class
public interface ApiInterface {
// getting same data in three different ways.
@GET("GetCompanyDetailByID")
Call<CompanyResponse> getDetailOfComapanies(@Query("CompanyID") int companyID);
@GET("GetCompanyDetailByID")
Call<ResponseBody> getRawDetailOfCompanies(@Query("CompanyID") int companyID);
@GET("{pathToAdd}")
Call<CompanyResponse> getDetailOfComapaniesWithPath(@Path("pathToAdd") String pathToAppend, @Query("CompanyID") int companyID);
}
并将此服务称为
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<CompanyResponse> companyResponseCall = apiService.getDetailOfComapanies(2);
//Call<CompanyResponse> companyResponseCall = apiService.getDetailOfComapaniesWithPath("GetCompanyDetailByID",2);
companyResponseCall.enqueue(new Callback<CompanyResponse>() {
@Override
public void onResponse(Call<CompanyResponse> call, Response<CompanyResponse> response) {
CompanyResponse comapnyResponse = response.body();
Boolean status = comapnyResponse.getStatus();
}
@Override
public void onFailure(Call<CompanyResponse> call, Throwable t) {
}
});
获取原始Json字符串
Call<ResponseBody> call = apiService.getRawDetailOfCompanies(2);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String jsonStr = response.body().string();
if(!jsonStr.isEmpty()){
Gson gson = new Gson();
JSONObject jObject = new JSONObject(jsonStr).getJSONObject("data");
//1st Method
Data dataKiType = gson.fromJson(jObject.toString(), Data.class);
dataKiType.getCompanyDetail();
//2nd method for creaing class or List at runTime
Type listType = new TypeToken<Data>(){}.getType();
Data yourClassList = new Gson().fromJson(jObject.toString(), listType);
yourClassList.getCompanyDetail();
} e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
您只需粘贴json即可使用http://www.jsonschema2pojo.org/创建业务对象。并选择源类型为JSON和注释样式为GSon
答案 6 :(得分:2)
查看此应用程序,演示将Google Revofit集成到Google Tasks API。
https://github.com/sschendel/SyncManagerAndroid-DemoGoogleTasks
MainActivity中的Activity AsyncTask中使用了Retrofit api(TaskApi)的示例,以及后台服务中Sync Adapter中的使用示例。
@ nPn回答中发表的文章的策略可能是一个更优雅的解决方案,但你至少可以看一下另一个有效的例子。
答案 7 :(得分:2)
首先,将所有内容放在MainActivity中都是不好的做法,最终会得到God object。
Retrofit site上的文档非常棒,所以我将阅读有关如何构建项目的问题。我为了演示目的写了一个非常小的应用程序。它从cat API加载猫,并且应该非常简单地跟踪正在发生的事情。
它有一个使用JSON或XML来解析服务数据的示例。您可以在https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit
找到它希望你能推断我为什么按照我的方式构建它。我很乐意回答您在评论中提出的任何问题并更新答案。
答案 8 :(得分:1)
找到一个小而完整而简洁的例子 https://github.com/square/retrofit/tree/master/samples
答案 9 :(得分:1)
初学者发现学习改造有点吓人。我准备了一个简化学习曲线的教程。有关详细信息,请参阅Retrofit android tutorial。
答案 10 :(得分:1)
首先,将此行添加到gradle文件
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup:otto:1.3.8'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
然后在OnCreate of Activity中创建对象
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client= new OkHttpClient
.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor(interceptor).build();
Gson gson=new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
Retrofit retrofit= new Retrofit.Builder()
.baseUrl("url")
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
创建一个iterface
public interface summaryListAPI {
//post
@FormUrlEncoded
@POST("index.php")
Call<summaryList> post(
@Field("status") String status,
@Field("sox") String sox
);
//get
@GET("yesbdeChatHistoryList/{userId}/")
Call<List<ChatTabTwoResp>> getFriends(
@Path("userId") int userId
);
}
创建课程
public class summaryList {
@SerializedName("bookingSummary") @Expose private List<summaryListData> status = new ArrayList<summaryListData>();
}
public class summaryListData {
@SerializedName("date") @Expose private String date;
}
将此方法添加到您的活动中
public void apiSummaryListMain(final Retrofit retrofit) {
retrofit.create(summaryListAPI.class).post("8547861657","100").enqueue(new Callback<summaryList>() {
@Override
public void onResponse(Call<summaryList> call, Response<summaryList> response) {
if (response.isSuccessful()) {
progressBar.setVisibility(View.INVISIBLE);
List<summaryListData> summary_List= response.body().getStatus();
}else{
}
}
@Override
public void onFailure(Call<summaryList> call, Throwable t) {
}
});
}
答案 11 :(得分:0)
正在运作
package com.keshav.gmailretrofitexampleworking.network;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
public static final String BASE_URL = "http://api.androidhive.info/json/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
==============================================
package com.keshav.gmailretrofitexampleworking.network;
import com.keshav.gmailretrofitexampleworking.models.Message;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
@GET("inbox.json")
Call<List<Message>> getInbox();
}
编译com.google.code.gson:gson:2.6.2&#39;
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
=============================================== ==
private void getInbox() {
swipeRefreshLayout.setRefreshing(true);
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<List<Message>> call = apiService.getInbox();
call.enqueue(new Callback<List<Message>>() {
@Override
public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
// clear the inbox
messages.clear();
// add all the messages
// messages.addAll(response.body());
// TODO - avoid looping
// the loop was performed to add colors to each message
Log.e("keshav","response" +response.body());
for (Message message : response.body()) {
// generate a random color
// TODO keshav Generate Random Color Here
message.setColor(getRandomMaterialColor("400"));
messages.add(message);
}
mAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
@Override
public void onFailure(Call<List<Message>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show();
swipeRefreshLayout.setRefreshing(false);
}
});
}
源代码 https://drive.google.com/open?id=0BzBKpZ4nzNzUVFRnVVkzc0JabUU
https://drive.google.com/open?id=0BzBKpZ4nzNzUc2FBdW00WkRfWW8
答案 12 :(得分:0)
开发自己的类型安全HTTP库以与REST API接口可能是一个真正的痛苦:您必须处理许多方面,例如建立连接,缓存,重试失败的请求,线程,响应解析,错误处理等等。另一方面,改造是一个精心策划,记录和测试的库,可以为您节省大量宝贵的时间和麻烦。
编译com.google.code.gson:gson:2.6.2&#39;
compile&#39; com.squareup.retrofit2:翻新:2.1.0&#39; //必修
compile&#39; com.squareup.retrofit2:converter-gson:2.1.0&#39; //用于改造转换
答案 13 :(得分:0)
我只是以一种非常简单的方式制作这个问题,你只需要安装一个插件并按照一些步骤在你的任何应用程序中实现改进。
已发布回答:Retrofit in android?
在Android工作室中添加(QAssist - Android Studio插件)Android插件。 (https://github.com/sakkeerhussain/QAssist)。
希望这会对你有所帮助。
答案 14 :(得分:0)
使用RxJava进行简单的改造+ okhttp集成
public WebService apiService(Context context) {
String mBaseUrl = context.getString(BuildConfig.DEBUG ? R.string.local_url : R.string.live_url);
int cacheSize = 5 * 1024 * 1024; // 5 MB
Cache cache = new Cache(context.getCacheDir(), cacheSize);
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.connectTimeout(120, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
//.addNetworkInterceptor(networkInterceptor)
.cache(cache)
.build();
return new Retrofit.Builder().baseUrl(mBaseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build().create(WebService.class);
}
答案 15 :(得分:0)
public interface APIService {
@POST(Constant.updateProfile)
@FormUrlEncoded
Call<ResponseBody> updateProfile(
@Field("user_id") String user_id,
@Field("first_name") String first_name,
@Field("last_name") String last_name
);
}
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public class Body {
// Check Status if Status True or False
String status;
String message;
String checksum;
}
public interface OnBodyResponseListner {
public void onSucces(Body response);
public void onFailure(Body response);
public void onBlankBody(Call<ResponseBody> call);
}
public static void setOnWebServiceCallListner(final Call<ResponseBody> t, final OnBodyResponseListner onBodyResponseListner) {
t.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
call.cancel();
Gson gson = new GsonBuilder().serializeNulls().create();
String json = response.body().string();
Log.d(TAG, json + " ~ Response ~ " + json);
Body body = gson.fromJson(json, Body.class);
if (body.getStatus().equalsIgnoreCase("true")) {
onBodyResponseListner.onSucces(body);
} else {
onBodyResponseListner.onFailure(body);
}
} catch (Exception e) {
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
onBodyResponseListner.onBlankBody(call);
Log.d(TAG, "~ Response Message Blank ~ " + t.getMessage() + " \n Localize Message ~ " + t.getLocalizedMessage() + " \n" + t.getStackTrace().toString());
}
});
}
APIService mService = RetrofitClient.getClient(Constant.BASE_URL).create(APIService.class);
Oprations.setOnWebServiceCallListner(mService.updateProfile("12",
"first_name",
"last,name"
), new OnBodyResponseListner() {
@Override
public void onSucces(Body response) {
}
@Override
public void onFailure(Body response) {
Toast.makeText(mContext, response.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onBlankBody(Call<ResponseBody> call) {
}
});
}
答案 16 :(得分:0)
compile 'com.squareup.retrofit:retrofit:1.7.1'
public class RetrofitClientInstance {
private Context context;
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit retrofit
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(BuildConfig.SERVER_URL)
.client(getRequestHeader())
.addConverterFactory(GsonConverterFactory.create());
public static HttpLoggingInterceptor setLogger() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
return logging;
}
public static <S> S createService(Class<S> serviceClass) {
if (!httpClient.interceptors().isEmpty()) {
httpClient.interceptors().clear();
}
httpClient.authenticator(new AccessTokenAuthenticator());
httpClient.readTimeout(60,TimeUnit.SECONDS);
httpClient.connectTimeout(60,TimeUnit.SECONDS);
httpClient.addInterceptor(setLogger());
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("LocalSystemDate", MyApplication.getInstance().getCurrentDateAndTimeWithTimeZone())
.addHeader("channel_id", AppConst.CHANNEL_ID)
.addHeader("Authorization", "Bearer" + " " + SharedPref.getsAccessToken())
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
private static OkHttpClient getRequestHeader() {
return new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
}
}
public interface GetDataService {
@Headers("Content-Type: application/json")
@POST("login")
Call<LoginResponseModel> loginUser(
@Body LoginBodyModel loginBodyModel
);
}
GetDataService service = RetrofitClientInstance.createService(GetDataService.class);
Call<LoginResponseModel> loginModelCall = service.loginUser(loginBodyModel);
loginModelCall.enqueue(new Callback<LoginResponseModel>() {
@Override
public void onResponse(Call<LoginResponseModel> call, Response<LoginResponseModel> response) {
}
@Override
public void onFailure(Call<LoginResponseModel> call, Throwable t) {
}
});