1.首先需要先加入相应依赖
dependencies{implementation 'com.squareup.okhttp3:okhttp:3.13.1'
implementation 'com.squareup.okio:okio:2.2.2'}
2.加入互联网权限
<!-- 互联网 --><uses-permission android:name="android.permission.INTERNET" /> <!-- 查看网络状态 --><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- 开关网络状态 --><uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
3.加入网络白名单
相关链接
package xxxxxxxxxxxxxxxxxxx;import android.util.Log;import java.io.IOException;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;public class HttpUtils {//发送get请求,带参数public static Map<String, Object> sendGet_body(String url, Map<String, String> map_header, Map<String, String> map_body) throws IOException, IOException {//添加headerHeaders.Builder builder_header = new Headers.Builder();for (String key : map_header.keySet()) {builder_header.add(key, Objects.requireNonNull(map_header.get(key)));}Headers headers = builder_header.build();//添加bodyHttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();for (String key : map_body.keySet()) {Log.d(key,Objects.requireNonNull(map_body.get(key)));urlBuilder.addQueryParameter(key, map_body.get(key));}//发送请求OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url(urlBuilder.build()).headers(headers).build();LocalTime startTime = LocalTime.now();//响应开始时间Response response = client.newCall(request).execute();LocalTime endTime = LocalTime.now();//响应结束时间int code = response.code();Log.d("HTTP返回代码",String.valueOf(code));if (code != 200) {Log.e("HTTP连接提示", "http连接失败");}Map<String, Object> map = new HashMap<>();map.put("code", code);Log.d("获取body内容",Objects.requireNonNull(response.body()).string());response.close();return map;}}
4.1 Request是OkHttp中访问的请求包含以下这些, URL请求的网络地址;method方法,包括get , post ; headers 请求头 body 请求体 。Builder是辅助类。
4.2 Call负责发送情况并接受返回,Response即OkHttp中的响应,
同步阻塞方法:
异步请求方法:
Callback中okhttp请求失败会调用 onFailure , 其他情况会调用 onResponse
4.3 Response包含内容
response.isSuccessful() //用来判断是否获取响应内容String string = response.body().string(); //body获取响应体,string转换为string类型字符串
完整的网络请求
package com.sina.myokhttp;import android.renderscript.RenderScript;import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;public class OkhttpGetORPost {private final OkHttpClient httpClient = new OkHttpClient();//同步阻塞的GET方法public void OkHttpGet() throws IOException {//防止在主UI线程中阻塞,使用后台线程ExecutorService executorService = Executors.newSingleThreadExecutor();executorService.submit(new Runnable() {@Overridepublic void run() {Request.Builder builder = new Request.Builder();builder.url("http://china.cn");Request request = builder.build();Call call = httpClient.newCall(request);try {//取出了返回的对象Response response = call.execute();if(response.isSuccessful()){//判断对象是否为空response.body().toString();}} catch (IOException e) {e.printStackTrace();}}});}//POST异步请求public void OkHttpPost(){//确定类型final MediaType JSON =MediaType.parse("application/json; charset=utf-8");Request.Builder builder = new Request.Builder();builder.url("http://china.cn");builder.post(RequestBody.create(JSON,""));Request request = builder.build();Call call = httpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic void onResponse(Call call, Response response) throws IOException {if(response.isSuccessful()){//判断对象是否为空response.body().toString();}}});}//携带Head的POST异步请求public void OkHttpPostHead(){Request.Builder builder = new Request.Builder();builder.url("http://china.cn");Request request = builder.build();Call call = httpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic void onResponse(Call call, Response response) throws IOException {//获取响应的CODEint code = response.code();//获取HeadsHeaders headers = response.headers();//获取Content-TypeString contentType = headers.get("Content-Type");}});}}