OK异步请求 + 解析 + Okhttp + 工具类 + GET + POST + Handler

package com.example.com.lixiaolong_04_27_.okhttp;
import android.os.Handler;
import android.os.Looper;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by 李小龙 on 2018/4/27.
 */

public class OkhttpUtils {
    private static OkhttpUtils instance;
    private OkHttpClient okHttpClient;
    private Handler handler;

    private OkhttpUtils(){
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();//拦截器
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClient = new OkHttpClient.Builder()//创建Ok
                .connectTimeout(15, TimeUnit.SECONDS)//连接超时
                .writeTimeout(20, TimeUnit.SECONDS)//写入超时
                .readTimeout(20, TimeUnit.SECONDS)//读取超时
                //.addInterceptor(new MyInterceptor())//添加拦截器
                .addInterceptor(logging)//添加拦截器
                .build();//
        handler = new Handler(Looper.getMainLooper());
    }
    //调用
    //调用
    //调用
    public static OkhttpUtils getInstance() {
        if (instance == null) {
            instance = new OkhttpUtils();
        }
        return instance;
    }
    //get方法
    //get方法
    //get方法
    public void doGet(String url, final OkhttpListener okhttpListener){
        //创建Request
        final Request request = new Request.Builder()
                .url(url)
                .build();
        //发送请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okhttpListener.No(e);
                    }
                });
            }
            public void onResponse(Call call,  Response response) throws IOException {
                //拿到服务器返回的数
                final String string = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okhttpListener.Ok(string);
                    }
                });
            }
        });
    }
    //post方法
    //post方法
    //post方法
    public void doPost(String url, Map<String, String> params, final OkhttpListener okhttpListener) {

        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        //创建FormBody
        FormBody formBody = builder.build();

        //创建Request
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        //请求数据
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okhttpListener.No(e);
                    }
                });
            }
            public void onResponse(Call call, Response response) throws IOException {
                //拿到服务器返回的数据
                final String string = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        okhttpListener.Ok(string);
                    }
                });
            }
        });
    }

}


实现接口回调方法
public interface OkhttpListener {
   void Ok(String str); //成功的方法
   void No(Exception e);//失败的方法
}

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用RxJava2 + Retrofit2 + OKHttp进行POST请求,可以按照以下步骤进行: 1. 添加依赖 在项目的build.gradle文件中添加以下依赖: ``` dependencies { implementation 'io.reactivex.rxjava2:rxjava:2.2.19' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.squareup.okhttp3:okhttp:4.9.1' } ``` 2. 创建Service接口 创建一个接口,用于定义POST请求的方法。例如: ``` public interface ApiService { @POST("login") Observable<LoginResponse> login(@Body LoginRequest request); } ``` 3. 创建Retrofit对象 在Application类或其他初始化类中,创建Retrofit对象: ``` public class MyApp extends Application { private static ApiService apiService; @Override public void onCreate() { super.onCreate(); // 创建OkHttpClient对象 OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .build(); // 创建Retrofit对象 Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://example.com/api/") .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); apiService = retrofit.create(ApiService.class); } public static ApiService getApiService() { return apiService; } } ``` 4. 发起POST请求 在需要发起POST请求的地方,可以使用以下代码: ``` LoginRequest request = new LoginRequest(); request.setUsername("admin"); request.setPassword("123456"); MyApp.getApiService().login(request) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<LoginResponse>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(LoginResponse response) { // 处理响应数据 } @Override public void onError(Throwable e) { // 处理异常 } @Override public void onComplete() { } }); ``` 上述代码中,我们首先创建了一个LoginRequest对象,用于存储要发送的数据。然后调用MyApp.getApiService().login(request)方法,发起POST请求。在这里,我们使用了RxJava2的Observable对象,将请求结果封装为一个可观察对象。使用subscribeOn(Schedulers.io())指定在IO线程中进行网络请求,使用observeOn(AndroidSchedulers.mainThread())指定在主线程中处理响应。最后通过subscribe方法订阅请求结果,处理响应数据或异常。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值