一.HTTPServlet服务端
环境:
1. JDK 1.8_u212
2. Tomcat 8.5.43
3. Intellij 2018.1
Java Enterprise
Web Application
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
@WebServlet(name = "RetrofitServlet", loadOnStartup = 1, urlPatterns = {"/retrofit"}) // urlPatterns即对外开放的接口 public class RetrofitServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("RetrofitServlet get请求到了"); doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("RetrofitServlet post请求到了"); String rootPath = getServletConfig().getServletContext().getRealPath("/"); System.out.println("程序目录:" + rootPath); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String userName = request.getParameter("userName"); // userName即客户端须要发送的参数的key System.out.println("用户:" + userName); if (null == userName || userName.trim().length() < 1) { response.setStatus(400); return; } // 这里进行业务处理 List resultData = new ArrayList(); // 这里进行业务处理 response.setStatus(200); PrintWriter writer = response.getWriter(); JSONObject object = new JSONObject(); object.put("resultData", resultData); writer.write(object.toString()); writer.flush(); } } |
二.Retrofit客户端
1.依赖
1 2 3 4 5 6 7 8 9 10 11 12 |
implementation 'io.reactivex.rxjava2:rxjava:2.2.10' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' implementation 'io.reactivex:rxjava-async-util:0.21.0' implementation 'com.squareup.okhttp3:okhttp:3.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0' implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0' |
2.Model
1 2 3 4 5 6 |
public class DataModel{ List resultData; // 变量名和HttpServlet返回的key一致 // get set } |
3.Service
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import io.reactivex.Observable; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; public interface RetrofitService { @POST("/retrofit") // 服务端servlet对外提供的接口 @FormUrlEncoded Observable<DataModel> getDatas(@Field("userName") String userName); // @Field("userName")即服务端要求的参数的key } |
4.OkHttp封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class BaseServiceManager { protected Gson gson = new GsonBuilder() // .setDateFormat("yyyy-MM-dd hh:mm:ss") // .create(); Interceptor headerInterceptor = new Interceptor() { // 请求头处理 @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Request.Builder requestBuilder = originalRequest.newBuilder()// .addHeader("Accept-Encoding", "gzip") // .addHeader("Accept", "application/json") // .addHeader("Content-Type", "application/json; charset=utf-8")// .method(originalRequest.method(), originalRequest.body()); // requestBuilder.addHeader("Authorization", "Bearer " + BaseConstant.TOKEN); // token验证 Request request = requestBuilder.build(); return chain.proceed(request); } }; protected HttpLoggingInterceptor loggingInterceptor = // 打印日志 new HttpLoggingInterceptor(// new HttpLoggingInterceptor.Logger() {// @Override public void log(String message) { if (message.length() < 16765168) { Log.e("ard_http_log", "网络原始数据:" + message); } } })// .setLevel(HttpLoggingInterceptor.Level.BODY); private OkHttpClient okHttpClient = new OkHttpClient // .Builder()// .addInterceptor(headerInterceptor) // 访问过滤器 .addInterceptor(loggingInterceptor) // 访问过滤器 .connectTimeout(5, TimeUnit.SECONDS) // 连接 超时时间 .writeTimeout(5, TimeUnit.SECONDS) // 写操作 超时时间 .readTimeout(5, TimeUnit.SECONDS) // 读操作 超时时间 .retryOnConnectionFailure(true) // 错误重连 .build(); protected Retrofit retrofit = new Retrofit // .Builder() // .baseUrl("http://www.gaohaiyan.com")// url统一的根节点 .client(okHttpClient) // .addConverterFactory(GsonConverterFactory.create(gson)) // json 解析 .addCallAdapterFactory(RxJava2CallAdapterFactory.create())// rxjava支持 .build(); } |
5.Retrofit封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; public class DataManager extends BaseServiceManager { private static DataManager instance; private RetrofitService request; private DataManager() { request = retrofit.create(RetrofitService.class); // service } public static DataManager getInstance() { if (null == instance) { synchronized (DataManager.class) { if (null == instance) { instance = new DataManager(); } } } return instance; } public void getDatas(String userName, final OnGetDataFinishedListener listener) { request.getDatas(userName)// .subscribeOn(Schedulers.newThread()) // 子线程执行 .observeOn(AndroidSchedulers.mainThread()) // 主线程响应 .subscribe( // new Consumer<DataModel>() { @Override public void accept(DataModel model) throws Exception { Log.e("", "请求反馈:" + (null == model ? "null" : model.getResultDate().size() + "")); if (null != listener) { listener.onGetModelFinished(model); } } }, // new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { Log.e("", "请求发生异常:" + throwable.getMessage()); if (null != listener) { listener.onGetModelFinished(null); } } }); } public interface OnGetDataFinishedListener { public void onGetModelFinished(DataModel model); } } |
6.请求
1 2 3 4 5 6 7 8 9 10 |
DateManager.OnDataFinishedListener listener = new DateManager.OnDataFinishedListener() { @Override public void onGetModelFinished(DataModel model) { Log.e("", "请求被响应了"); } }; DateManager.getInstance().getDatas("威格灵", listener); |
end
声明
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/2427.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设