Android--OkHttp的使用

简单的get和post请求

依赖

    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.2'
    implementation 'net.qiujuer.common:okhttp:3.0.0'

get请求

//设置它的相关参数
public final static int CONNECT_TIMEOUT = 60;
public final static int READ_TIMEOUT = 100;
public final static int WRITE_TIMEOUT = 60;
public static final OkHttpClient client = new OkHttpClient.Builder()
   .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
   .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
   .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
   .build();
public String get(String url) throws IOException{
    
    
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
    
    
            String res = response.body().string();
            return res;
        }else{
    
    
            throw new IOException("Unexpected code " + response);
        }
    }

post请求(带参数)

public static String post1(String url,String json) throws IOException {
    
    //json为要传的参数
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Log.i("json:",json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
    
    
            String res = response.body().string();
            Log.i("返回结果:", res);
            return res;
        } else {
    
    
            throw new IOException("Unexpected code " + response);
        }
    }

post带token请求

public String post(String url, String json) throws IOException {
    
    
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON,json);
        //Log.i("json:",json);
        //SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user",getActivity().MODE_PRIVATE);
        //String token = sharedPreferences.getString("token",null);
        Log.i("token值",token);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("authorization",token)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
    
    
            String res = response.body().string();
            Log.i("返回结果:", res);
            return res;
        } else {
    
    
            throw new IOException("Unexpected code " + response);
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_43337254/article/details/112876884
今日推荐