OkHttp学习(1)--同步和异步(get、post键值对、post带map、请求头体封装json)

2024-08-31 23:08

本文主要是介绍OkHttp学习(1)--同步和异步(get、post键值对、post带map、请求头体封装json),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

之前学习过Volley的种种用法,点击如下链接可以参考
如果想对Volley有所了解,可以看我这5篇关于Volley的实践代码

今天来学习下OkHttp的学习,这篇博客主要是来了解OkHttp同步和异步—(get、post键值对、post带map、请求头体封装json)
下一篇去了解文件上传、图片下载

为了快速使用,没有去研究源码了,但是看过Volley的源码,我感觉本质上也是想通的,就直接通过demo的跑通方式来了解把

我通过http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly这个进行测试
返回的Json格式如下:

{"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}

首先看主页布局
这里写图片描述

先来了解下关于同步请求的方法

1、先看第一种,同步get请求

      new Thread() {@Overridepublic void run() {try {Response response =  OkHttpManger.getInstance().getSync("http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly");if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity", "getSync:" + responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();

我们在第一个方法里面,看看OkHttpManger做了什么操作?
OkHttpManger.getInstance().getSync(“http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly“);

  private Handler okHttpHandler;private OkHttpClient mOkHttpClient;private OkHttpManger(){this.mOkHttpClient = SaflyApplication.getInstance().getUnsafeOkHttpClient();this.okHttpHandler = new Handler(Looper.getMainLooper());}public static final OkHttpManger getInstance(){return SingleFactory.manger;}private static final class SingleFactory{private static final OkHttpManger manger = new OkHttpManger();}

我们本篇博客,需要测试在请求体传json的例子,由于公司是https的,我就直接信任所有的证书了,
在getInstance中就是一个单利模式,然后封装了一个handler用于主线程更新使用
getUnsafeOkHttpClient我是网上找的代码–我没有跟公司的进行认证请求(这个不是这篇的学习了解重点)

 public static OkHttpClient getUnsafeOkHttpClient() {try {final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[]{};}}};final SSLContext sslContext = SSLContext.getInstance("SSL");sslContext.init(null, trustAllCerts, new java.security.SecureRandom());final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();OkHttpClient.Builder builder = new OkHttpClient.Builder();builder.sslSocketFactory(sslSocketFactory);builder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});OkHttpClient okHttpClient = builder.connectTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();return okHttpClient;} catch (Exception e) {throw new RuntimeException(e);}}

OkHttpClient okHttpClient = builder.connectTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();这里就是okHttpClient的操作

在getSync方法中,就是调用了ok的方法,构造请求Request ,Call 然后直接执行即可,返回一个Response

   public Response getSync(final String url) throws IOException {final Request request = new Request.Builder().url(url).build();final Call call = mOkHttpClient.newCall(request);return call.execute();}

然后,进行更新即可

if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity", "getSync:" + responseStr);}

2、先看第1种,同步post请求,添加params方式

 final OkHttpManger.Param param1 = new OkHttpManger.Param("phone","13429667914");final OkHttpManger.Param param2 = new OkHttpManger.Param("key","safly");new Thread() {@Overridepublic void run() {try {Response response =  OkHttpManger.getInstance().postSync("http://apis.juhe.cn/mobile/get",param1,param2);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams1:"+responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();
    final Request request = buildPostRequst(url, params);final Call call = mOkHttpClient.newCall(request);return call.execute();}

这里就看看buildPostRequst方法

private Request buildPostRequst(String url, Param... params){if(params == null){params = new Param[0];}FormBody.Builder builder = new FormBody.Builder();for(Param param:params){builder.add(param.key,param.value);}return new Request.Builder().url(url).post(builder.build()).build();}

然后依然在主界面进行更新即可

3、先看第3种,同步post请求,添加map集合方式

final HashMap<String,String> maps = new HashMap<>();maps.put("phone","13429667914");maps.put("key","safly");new Thread() {@Overridepublic void run() {try {Response response =  OkHttpManger.getInstance().postSync("http://apis.juhe.cn/mobile/get",maps);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams2:"+responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();
 public Response postSync(String url, Map<String,String> params) throws IOException {final Request request = buildPostRequst(url, params);final Call call = mOkHttpClient.newCall(request);return call.execute();}
  private Request buildPostRequst(String url, Map<String,String> params){Request request = null;if(params == null){params = new HashMap<>();}if(params != null){Set<Map.Entry<String,String>> entries = params.entrySet();FormBody.Builder builder = new FormBody.Builder();for(Map.Entry<String,String> entry:entries){builder.add(entry.getKey(),entry.getValue());}request = new Request.Builder().url(url).post(builder.build()).build();}return request;}

代码简单,然后依然是在主界面进行其他操作

4、先看第4种,同步post请求,添加Json请求体请求方式

  try {Json = createJson();Log.i("MainActivity","postSyncByParams2 Json:"+Json);} catch (JSONException e) {e.printStackTrace();}new Thread() {@Overridepublic void run() {try {Response response =  OkHttpManger.getInstance().postSyncJson("https://www.imlianxi.com:xxxx/AppFeedback", Json);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams2:"+responseStr);}else{Log.i("MainActivity","postSyncByParams2 error");}} catch (IOException e) {e.printStackTrace();}}}.start();

这是我公司的项目ulr,我用xxxx号码替代了,不方便暴露,嘿嘿嘿
我这里构造json直接用的JSONObject
这里写图片描述

   private String createJson() throws JSONException {JSONObject jsonObject = new JSONObject();JSONObject body = new JSONObject();body.put("phoneimei", "353490061934846");body.put("context", "反馈");JSONObject head = new JSONObject();head.put("app_type", "3");head.put("os_type", "android");head.put("osversion", "5.1.1");head.put("appversion", "1.0");head.put("devicefactory", "LGE");head.put("devicemodel", "AOSP on HammerHead");JSONObject Request = new JSONObject();Request.put("body", body);Request.put("head", head);jsonObject.put("Request", Request);return jsonObject.toString();}
 public Response postSyncJson(String url, String json) throws IOException {final RequestBody requestBody = RequestBody.create(JSON_TYPE, json);final Request request = new Request.Builder().url(url).post(requestBody).build();return mOkHttpClient.newCall(request).execute();}

然后在主界面做其他操作即可

以上就是同步请求,我们接下来看看异步操作请求

5、先看第5种,异步get请求

  try {OkHttpManger.getInstance().getAsync("http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly", new OKHttpUICallback.ResultCallback<Result>() {@Overridepublic void onSuccess(Result result) {Log.i("MainActivity","result:"+result.toString());}@Overridepublic void onError(Call call, IOException e) {}});} catch (IOException e) {e.printStackTrace();}

用这个进行测试http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly
返回的格式

{"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}

封装个对象把如下

package utils;/*** {"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}*/
public class Result {private String resultcode;private String reason;private String result;private int error_code;public Result(String resultcode, String reason, String result, int error_code) {this.resultcode = resultcode;this.reason = reason;this.result = result;this.error_code = error_code;}public Result() {}@Overridepublic String toString() {return "Result{" +"resultcode='" + resultcode + '\'' +", reason='" + reason + '\'' +", result='" + result + '\'' +", error_code=" + error_code +'}';}public String getResultcode() {return resultcode;}public String getReason() {return reason;}public String getResult() {return result;}public int getError_code() {return error_code;}public void setResultcode(String resultcode) {this.resultcode = resultcode;}public void setReason(String reason) {this.reason = reason;}public void setResult(String result) {this.result = result;}public void setError_code(int error_code) {this.error_code = error_code;}
}

看看方法把:

try {OkHttpManger.getInstance().getAsync("http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly", new OKHttpUICallback.ResultCallback<Result>() {@Overridepublic void onSuccess(Result result) {Log.i("MainActivity","result:"+result.toString());}@Overridepublic void onError(Call call, IOException e) {}});} catch (IOException e) {e.printStackTrace();}
  public void getAsync(final String url, final OKHttpUICallback.ResultCallback callback)throws IOException {final Request request = new Request.Builder().url(url).build();final Call call = mOkHttpClient.newCall(request);deliveryResult(call, callback);}

在楼上的代码,带一个回调 OKHttpUICallback.ResultCallback callback
然后请求完毕后,在次进行接口回调,去主界面进行相应操作

 private void deliveryResult(final Call call, final OKHttpUICallback.ResultCallback callback){call.enqueue(new Callback() {@Overridepublic void onFailure(final Call call, final IOException e) {okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (callback != null) {callback.onError(call, e);}}});}@Overridepublic void onResponse(Call call, Response response) throws IOException {if(callback != null){final Object object = JSON.parseObject(response.body().string(), callback.mType);okHttpHandler.post(new Runnable() {@Overridepublic void run() {callback.onSuccess(object);}});}}});}

我们看看OKHttpUICallback.ResultCallback callback

public static abstract class ResultCallback<T>{public Type mType;public ResultCallback(){mType = getSuperclassTypeParameter(getClass());}private static Type getSuperclassTypeParameter(Class<?> subclass){Type superclass = subclass.getGenericSuperclass();if(superclass instanceof Class){throw new RuntimeException("Miss type parameter");}ParameterizedType parameterizedType = (ParameterizedType)superclass;return parameterizedType.getActualTypeArguments()[0];}public abstract void onSuccess(T result);public abstract void onError(Call call, IOException e);}

我这里是用了阿里的封装类jar

 if(callback != null){final Object object = JSON.parseObject(response.body().string(), callback.mType);okHttpHandler.post(new Runnable() {@Overridepublic void run() {callback.onSuccess(object);}});}

封装完毕,post到主线程做其他操作即可

67、第6、7种省略–代码大同小异,下面代码附上

8、看第8种,异步post传json请求
这个我们用另外一个

 try {Json = createJson();Log.i("MainActivity","postSyncByParams2 Json:"+Json);} catch (JSONException e) {e.printStackTrace();}try {OkHttpManger.getInstance().postAsyncJsonn("https://www.imlianxi.com:xxxx/AppFeedback", Json, new OkHttpManger.MyCallback() {@Overridepublic void onSuccess(String result) {Log.i("MainActivity","result----"+result);}@Overridepublic void onFailture() {}});} catch (IOException e) {e.printStackTrace();}
interface MyCallback{void onSuccess(String result);void onFailture();}public void postAsyncJsonn(String url, String json, MyCallback mCallback) throws IOException {final RequestBody requestBody = RequestBody.create(JSON_TYPE, json);final Request request = new Request.Builder().url(url).post(requestBody).build();deliveryResult(mOkHttpClient.newCall(request),mCallback);}private void deliveryResult(final Call call, final  MyCallback mCallback){call.enqueue(new Callback() {@Overridepublic void onFailure(final Call call, final IOException e) {okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (mCallback !=null){mCallback.onFailture();}}});}@Overridepublic void onResponse(Call call, final  Response response) throws IOException {final String responseStr = response.body().string();okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (mCallback != null) {mCallback.onSuccess(responseStr);}}});}});}

定义了一个接口,不过没有封装对象类,收到相应后,在通过一个接口回调即可


———-以下是代码———————–以下是代码—————以下是代码————————–

MainActivity

package com.example.administrator.myapplication;import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import org.json.JSONException;
import org.json.JSONObject;import java.io.IOException;
import java.util.HashMap;import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import utils.Result;/*** http://www.imooc.com/api/teacher?type=4&num=30*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {private String responseStr;private Handler mHandler;TextView textView;Button getSync,postSyncByParams1,postSyncByParams2,postSyncJson;Button getAsync,postAsyncParams,postAsyncByParams2,postAsyncJson;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = (TextView) findViewById(R.id.textView);//同步getSync = (Button) findViewById(R.id.getSync);postSyncByParams1 = (Button) findViewById(R.id.postSyncByParams1);postSyncByParams2 = (Button) findViewById(R.id.postSyncByParams2);postSyncJson = (Button) findViewById(R.id.postSyncJson);//异步getAsync = (Button) findViewById(R.id.getAsync);postAsyncParams = (Button) findViewById(R.id.postAsyncParams);postAsyncByParams2 = (Button) findViewById(R.id.postAsyncByParams2);postAsyncJson = (Button) findViewById(R.id.postAsyncJson);getSync.setOnClickListener(this);postSyncByParams1.setOnClickListener(this);postSyncByParams2.setOnClickListener(this);postSyncJson.setOnClickListener(this);getAsync.setOnClickListener(this);postAsyncParams.setOnClickListener(this);postAsyncByParams2.setOnClickListener(this);postAsyncJson.setOnClickListener(this);mHandler = new Handler(){public void handleMessage(android.os.Message msg) {if (msg.what == 1) {textView.setText(responseStr);}};};}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.getSync:new Thread() {@Overridepublic void run() {try {Response response =  OkHttpManger.getInstance().getSync("http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly");if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity", "getSync:" + responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();break;case R.id.postSyncByParams1:final OkHttpManger.Param param1 = new OkHttpManger.Param("phone","13429667914");final OkHttpManger.Param param2 = new OkHttpManger.Param("key","safly");new Thread() {@Overridepublic void run() {try {Response response =  OkHttpManger.getInstance().postSync("http://apis.juhe.cn/mobile/get",param1,param2);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams1:"+responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();break;case R.id.postSyncByParams2:final HashMap<String,String> maps = new HashMap<>();maps.put("phone","13429667914");maps.put("key","safly");new Thread() {@Overridepublic void run() {try {Response response =  OkHttpManger.getInstance().postSync("http://apis.juhe.cn/mobile/get",maps);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams2:"+responseStr);}} catch (IOException e) {e.printStackTrace();}}}.start();break;case R.id.postSyncJson:try {Json = createJson();Log.i("MainActivity","postSyncByParams2 Json:"+Json);} catch (JSONException e) {e.printStackTrace();}new Thread() {@Overridepublic void run() {try {Response response =  OkHttpManger.getInstance().postSyncJson("https://www.imlianxi.com:7773/AppFeedback", Json);if (response.isSuccessful()){responseStr = response.body().string();mHandler.sendEmptyMessage(1);Log.i("MainActivity","postSyncByParams2:"+responseStr);}else{Log.i("MainActivity","postSyncByParams2 error");}} catch (IOException e) {e.printStackTrace();}}}.start();break;//{"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}case R.id.getAsync:try {OkHttpManger.getInstance().getAsync("http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly", new OKHttpUICallback.ResultCallback<Result>() {@Overridepublic void onSuccess(Result result) {Log.i("MainActivity","result:"+result.toString());}@Overridepublic void onError(Call call, IOException e) {}});} catch (IOException e) {e.printStackTrace();}break;case R.id.postAsyncParams:final OkHttpManger.Param param11 = new OkHttpManger.Param("phone","13429667914");final OkHttpManger.Param param22 = new OkHttpManger.Param("key","safly");try {OkHttpManger.getInstance().postAsync("http://apis.juhe.cn/mobile/get", new OKHttpUICallback.ResultCallback<Result>() {@Overridepublic void onSuccess(Result result) {Log.i("MainActivity", "result:" + result.toString());}@Overridepublic void onError(Call call, IOException e) {}},param11,param22);} catch (IOException e) {e.printStackTrace();}break;case R.id.postAsyncByParams2:final HashMap<String,String> mapss = new HashMap<>();mapss.put("phone","13429667914");mapss.put("key","safly");try {OkHttpManger.getInstance().postAsync("http://apis.juhe.cn/mobile/get", new OKHttpUICallback.ResultCallback<Result>() {@Overridepublic void onSuccess(Result result) {Log.i("MainActivity", "result:" + result.toString());}@Overridepublic void onError(Call call, IOException e) {}},mapss);} catch (IOException e) {e.printStackTrace();}break;/*** {"Response":{"head":{"statuscode":"113166","statusmsg":"Important parameter error"}}}*/case R.id.postAsyncJson:try {Json = createJson();Log.i("MainActivity","postSyncByParams2 Json:"+Json);} catch (JSONException e) {e.printStackTrace();}try {OkHttpManger.getInstance().postAsyncJsonn("https://www.imlianxi.com:7773/AppFeedback", Json, new OkHttpManger.MyCallback() {@Overridepublic void onSuccess(String result) {Log.i("MainActivity","result----"+result);}@Overridepublic void onFailture() {}});} catch (IOException e) {e.printStackTrace();}break;case R.id.uploadAsync1:case R.id.uploadAsync2:case R.id.uploadSync1:case R.id.uploadSync2:Toast.makeText(MainActivity.this, "暂时无接口测试后续补充。。。", Toast.LENGTH_SHORT).show();break;case R.id.downloadAsync:break;}}String Json = null;private String createJson() throws JSONException {JSONObject jsonObject = new JSONObject();JSONObject body = new JSONObject();body.put("phoneimei", "353490061934846");body.put("context", "反馈");JSONObject head = new JSONObject();head.put("app_type", "3");head.put("os_type", "android");head.put("osversion", "5.1.1");head.put("appversion", "1.0");head.put("devicefactory", "LGE");head.put("devicemodel", "AOSP on HammerHead");JSONObject Request = new JSONObject();Request.put("body", body);Request.put("head", head);jsonObject.put("Request", Request);return jsonObject.toString();}
}

SaflyApplication

package com.example.administrator.myapplication;import android.app.Application;import java.util.concurrent.TimeUnit;import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;import okhttp3.OkHttpClient;public class SaflyApplication extends Application {private static SaflyApplication instance;@Overridepublic void onCreate() {super.onCreate();this.instance = this;}public static SaflyApplication getInstance() {return instance;}public static OkHttpClient getUnsafeOkHttpClient() {try {final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[]{};}}};final SSLContext sslContext = SSLContext.getInstance("SSL");sslContext.init(null, trustAllCerts, new java.security.SecureRandom());final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();OkHttpClient.Builder builder = new OkHttpClient.Builder();builder.sslSocketFactory(sslSocketFactory);builder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});OkHttpClient okHttpClient = builder.connectTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();return okHttpClient;} catch (Exception e) {throw new RuntimeException(e);}}
}

OkHttpManger

package com.example.administrator.myapplication;import android.os.Handler;
import android.os.Looper;
import android.util.Log;import com.alibaba.fastjson.JSON;import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;/*** OkHttp 工具类,* get的同步异步请求* post的json字符串同步异步上传* post的键值对同步异步上传* post文件异步上传,回调结果以及进度* 异步下载文件,回调结果以及进度** Created by Seeker on 2016/6/24.*/
public final class OkHttpManger {private static final String TAG = "OkHttpManger";private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");private Handler okHttpHandler;private OkHttpClient mOkHttpClient;private OkHttpManger(){this.mOkHttpClient = SaflyApplication.getInstance().getUnsafeOkHttpClient();this.okHttpHandler = new Handler(Looper.getMainLooper());}public static final OkHttpManger getInstance(){return SingleFactory.manger;}private static final class SingleFactory{private static final OkHttpManger manger = new OkHttpManger();}/*** 同步get请求** @param url 地址* @return Response 返回数据*/public Response getSync(final String url) throws IOException {final Request request = new Request.Builder().url(url).build();final Call call = mOkHttpClient.newCall(request);return call.execute();}/*** 同步post请求,键值对** @param url 地址* @param params 参数*               Request.Builder().url(url).post(builder.build()).build();*/public Response postSync(String url, Param... params) throws IOException {final Request request = buildPostRequst(url, params);final Call call = mOkHttpClient.newCall(request);return call.execute();}/*** 同步post请求,键值对** @param url 地址* @param params 参数*/public Response postSync(String url, Map<String,String> params) throws IOException {final Request request = buildPostRequst(url, params);final Call call = mOkHttpClient.newCall(request);return call.execute();}/*** post同步请求,提交Json数据** @param url 地址* @param json json格式的字符串* @return Response*/public Response postSyncJson(String url, String json) throws IOException {final RequestBody requestBody = RequestBody.create(JSON_TYPE, json);final Request request = new Request.Builder().url(url).post(requestBody).build();return mOkHttpClient.newCall(request).execute();}/*** 同步基于post的文件上传* @param url 地址* @param file 提交的文件* @param fileKey 提交的文件key* @return Response*/public Response uploadSync(String url, File file, String fileKey) throws IOException {return uploadSync(url, new File[]{file}, new String[]{fileKey}, new Param[0]);}/*** 同步基于post的文件上传* @param url 地址* @param files 提交的文件数组* @param fileKeys 提交的文件数组key* @param params 提交的键值对* @return Response*/public Response uploadSync(String url, File[] files, String[] fileKeys, Param[] params) throws IOException {final RequestBody requestBody = buildMultipartFormRequestBody(files, fileKeys, params);final Request request = new Request.Builder().url(url).post(requestBody).build();return mOkHttpClient.newCall(request).execute();}//*** 异步get请求** @param url 地址* @param callback 回调*/public void getAsync(final String url, final OKHttpUICallback.ResultCallback callback)throws IOException {final Request request = new Request.Builder().url(url).build();final Call call = mOkHttpClient.newCall(request);deliveryResult(call, callback);}/*** post异步请求,键值对* @param url :地址* @param params :参数* @param callback :回调*/public void postAsync(String url, OKHttpUICallback.ResultCallback callback, Param... params) throws IOException {final Call call = mOkHttpClient.newCall(buildPostRequst(url, params));deliveryResult(call,callback);}/*** post异步请求,键值对* @param url :地址* @param params :参数* @param callback :回调*/public void postAsync(String url, OKHttpUICallback.ResultCallback callback, Map<String,String> params) throws IOException {final Call call = mOkHttpClient.newCall(buildPostRequst(url, params));deliveryResult(call,callback);}/*** post异步请求,提交Json数据** @param url 地址* @param json json格式的字符串*/public void postAsyncJson(String url, String json, OKHttpUICallback.ResultCallback callback) throws IOException {final RequestBody requestBody = RequestBody.create(JSON_TYPE, json);final Request request = new Request.Builder().url(url).post(requestBody).build();deliveryResult(mOkHttpClient.newCall(request),callback);}interface MyCallback{void onSuccess(String result);void onFailture();}public void postAsyncJsonn(String url, String json, MyCallback mCallback) throws IOException {final RequestBody requestBody = RequestBody.create(JSON_TYPE, json);final Request request = new Request.Builder().url(url).post(requestBody).build();deliveryResult(mOkHttpClient.newCall(request),mCallback);}private void deliveryResult(final Call call, final  MyCallback mCallback){call.enqueue(new Callback() {@Overridepublic void onFailure(final Call call, final IOException e) {okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (mCallback !=null){mCallback.onFailture();}}});}@Overridepublic void onResponse(Call call, final  Response response) throws IOException {final String responseStr = response.body().string();okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (mCallback != null) {mCallback.onSuccess(responseStr);}}});}});}/*** 生成request* @param url* @param params* @return*/private Request buildPostRequst(String url, Param... params){if(params == null){params = new Param[0];}FormBody.Builder builder = new FormBody.Builder();for(Param param:params){builder.add(param.key,param.value);}return new Request.Builder().url(url).post(builder.build()).build();}/*** 生成request* @param url* @param params* @return*/private Request buildPostRequst(String url, Map<String,String> params){Request request = null;if(params == null){params = new HashMap<>();}if(params != null){Set<Map.Entry<String,String>> entries = params.entrySet();FormBody.Builder builder = new FormBody.Builder();for(Map.Entry<String,String> entry:entries){builder.add(entry.getKey(),entry.getValue());}request = new Request.Builder().url(url).post(builder.build()).build();}return request;}/*** 生成post提交时的分块request* @param files* @param fileKeys* @param params* @return*/private RequestBody buildMultipartFormRequestBody(File[] files, String[] fileKeys, Param[] params){if(params == null){params = new Param[0];}MultipartBody.Builder builder = new MultipartBody.Builder();for(Param param:params){builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),RequestBody.create(null, param.value));}if(files == null){files = new File[0];}if(fileKeys == null){fileKeys = new String[0];}if(fileKeys.length != files.length){throw new ArrayStoreException("fileKeys.length != files.length");}RequestBody fileBody = null;int length = files.length;for(int i = 0;i<length;i++){File file = files[i];String fileName = file.getName();fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)),file);//TODO 根据文件名设置contentTypebuilder.addPart(Headers.of("Content-Disposition","form-data; name=\"" + fileKeys[i] + "\"; fileName=\"" + fileName + "\""),fileBody);}return builder.build();}private String guessMimeType(String path){FileNameMap fileNameMap = URLConnection.getFileNameMap();String type = fileNameMap.getContentTypeFor(path);if(type == null){type = "application/octet-stream";}return type;}/*** 获取文件名** @param path*/private String getFileName(String path){int lastSeparaorIndex = path.lastIndexOf("/");return (lastSeparaorIndex < 0) ? path : path.substring(lastSeparaorIndex + 1, path.length());}/*** 数据请求并处理* @param call* @param callback*/private void deliveryResult(final Call call, final OKHttpUICallback.ResultCallback callback){call.enqueue(new Callback() {@Overridepublic void onFailure(final Call call, final IOException e) {okHttpHandler.post(new Runnable() {@Overridepublic void run() {if (callback != null) {callback.onError(call, e);}}});}@Overridepublic void onResponse(Call call, Response response) throws IOException {if(callback != null){final Object object = JSON.parseObject(response.body().string(), callback.mType);okHttpHandler.post(new Runnable() {@Overridepublic void run() {callback.onSuccess(object);}});}}});}public static final class Param{private String key;private String value;public Param(String key, String value){this.key = key;this.value = value;}}
}

OKHttpUICallback

package com.example.administrator.myapplication;import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;import okhttp3.Call;
import okhttp3.Response;/*** Created by safly on 2016/9/1.** 回调主线程的接口*/
public class OKHttpUICallback {/*** 异步回调接口*/public static abstract class ResultCallback<T>{public Type mType;public ResultCallback(){mType = getSuperclassTypeParameter(getClass());}private static Type getSuperclassTypeParameter(Class<?> subclass){Type superclass = subclass.getGenericSuperclass();if(superclass instanceof Class){throw new RuntimeException("Miss type parameter");}ParameterizedType parameterizedType = (ParameterizedType)superclass;return parameterizedType.getActualTypeArguments()[0];}public abstract void onSuccess(T result);public abstract void onError(Call call, IOException e);}/*** 带有进度的上传、下载回调接口*/public interface ProgressCallback{void onSuccess(Call call, Response response, String path);void onProgress(long byteReadOrWrite, long contentLength, boolean done);void onError(Call call, IOException e);}
}

Result

package utils;/*** {"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}*/
public class Result {private String resultcode;private String reason;private String result;private int error_code;public Result(String resultcode, String reason, String result, int error_code) {this.resultcode = resultcode;this.reason = reason;this.result = result;this.error_code = error_code;}public Result() {}@Overridepublic String toString() {return "Result{" +"resultcode='" + resultcode + '\'' +", reason='" + reason + '\'' +", result='" + result + '\'' +", error_code=" + error_code +'}';}public String getResultcode() {return resultcode;}public String getReason() {return reason;}public String getResult() {return result;}public int getError_code() {return error_code;}public void setResultcode(String resultcode) {this.resultcode = resultcode;}public void setReason(String reason) {this.reason = reason;}public void setResult(String result) {this.result = result;}public void setError_code(int error_code) {this.error_code = error_code;}
}

这篇关于OkHttp学习(1)--同步和异步(get、post键值对、post带map、请求头体封装json)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1125251

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

服务器集群同步时间手记

1.时间服务器配置(必须root用户) (1)检查ntp是否安装 [root@node1 桌面]# rpm -qa|grep ntpntp-4.2.6p5-10.el6.centos.x86_64fontpackages-filesystem-1.41-1.1.el6.noarchntpdate-4.2.6p5-10.el6.centos.x86_64 (2)修改ntp配置文件 [r

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

系统架构师考试学习笔记第三篇——架构设计高级知识(20)通信系统架构设计理论与实践

本章知识考点:         第20课时主要学习通信系统架构设计的理论和工作中的实践。根据新版考试大纲,本课时知识点会涉及案例分析题(25分),而在历年考试中,案例题对该部分内容的考查并不多,虽在综合知识选择题目中经常考查,但分值也不高。本课时内容侧重于对知识点的记忆和理解,按照以往的出题规律,通信系统架构设计基础知识点多来源于教材内的基础网络设备、网络架构和教材外最新时事热点技术。本课时知识