【安卓开发】Android初级开发(okhttp3发送带header与带参数的GET请求)
生活随笔
收集整理的這篇文章主要介紹了
【安卓开发】Android初级开发(okhttp3发送带header与带参数的GET请求)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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");}});}}?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的【安卓开发】Android初级开发(okhttp3发送带header与带参数的GET请求)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【H.264/AVC视频编解码技术】第四
- 下一篇: 购房合同备案号几位数字(购房合同备案号几