OkHttp官网 http://square.github.io/okhttp/
GitHub官方 https://github.com/square/okhttp
Okhttp现在来说应该算很厉害的网络请求的框架了。
当然,这也是拾人牙慧,我特么第三方框架都用上了还管什么拾人牙慧。
开搞!!!!!
推荐个鸿洋大神的http://blog.csdn.net/lmj623565791/article/details/49734867
先上一个回调接口,只有两个简单的方法;
/**
* @auther Fsnzzz
* @date 2018.11.20
* @param onSucceed() : 成功回调
* @param onFailure() : 失败回调
*/
public interface NetCallBack {
void onSucceed(Response response);
void onFailure(String msg);
}
同步get请求
/**
* call.execute();
* 同步GET请求 因为是耗时操作,要在子线程里执行 new Thread(new Runnable())
* @param url 请求链接
* @param netCallBack
* @throws IOException
*/
private void onSyncGet(String url,NetCallBack netCallBack) throws IOException {
//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.get()//默认get,可省略
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
//请求加入调度
Response response = call.execute();
netCallBack.onSucceed(response);
// response.body().string();
}
异步get请求
/**
* On async get. 异步GET请求
* call.enqueue()
* @param netCallBack the net call back
* @author Fsnzzz
*/
private void onAsyncGET(String url, final NetCallBack netCallBack) {
//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.get()//默认get,可省略
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
//请求加入调度
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 请求失败的回调
netCallBack.onFailure(e.getMessage().toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//成功的回调
netCallBack.onSucceed(response);
// response.body().string();
}
});
}
回调的接口还是那个接口
public interface NetCallBack {
void onSucceed(Response response);
void onFailure(String msg);
}
同步post请求 带参
/**
* 同步POST请求
* @param url
* @param bodyParams
* @return
*/
private Response onSyncPostBody(String url, Map<String,String> bodyParams) throws IOException {
RequestBody body = getBodyParams(bodyParams);
Request.Builder builder = new Request.Builder();
Request request = builder.post(body)
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
//请求加入调度
Response response = call.execute();
return response;
}
/**
* 设置bodyParams
* @param bodyParams
* @return RequestBody
*/
private RequestBody getBodyParams(Map<String,String> bodyParams){
RequestBody body = null;
FormBody.Builder formBody = new FormBody.Builder();
if (bodyParams != null){
Iterator<String> iterator = bodyParams.keySet().iterator();
String key = "";
while (iterator.hasNext()){
key = iterator.next().toString();
formBody.add(key,bodyParams.get(key));
}
}
return formBody.build();
}
post请求的时候是要携带参数的,参数是包含在请求体中的;所以我们通过FormBody.Builder。添加多个String键值对,然后去构造RequestBody,最后完成我们Request的构造。
异步post请求带参
/**
* 异步post请求
* @param url
* @param bodyParams
*/
private void onAsyncPOST_Body(String url,Map<String,String> bodyParams,NetCallBack netCallBack){
Request.Builder builder = new Request.Builder();
Request request = builder.post(getBodyParams(bodyParams))
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCallBack.onFailure(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
netCallBack.onSucceed(response);
}
});
}
由于公司后台给的接口不需要进行传参,所有图片上传到同一个后台文件夹内,上传成功后返回一个图片链接,然后再把图片链接上传到相关的后台。
/**
* 图片上传 不带参数的上传,
* @param url
* @param body
* @param imgs
* @param netCallBack
*/
public void onUpImage(String url, JSONObject data,NetCallBack netCallBack){
MultipartBody.Builder builder = new MultipartBody.Builder();
if (data != null){
Iterator<String> keys = data.keys();
while (keys.hasNext()){
File file = null;
try {
String key = keys.next();
file = new File(data.getString(key));
builder.addFormDataPart(key, file.getAbsolutePath(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
builder.setType(MultipartBody.FORM);
MultipartBody multipartBody = builder.build();
Request request = new Request.Builder()
.url(url)
.post(multipartBody)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCallBack.onFailure(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
netCallBack.onSucceed(response);
}
});
}
源码Utils,还有文件下载没写,好吧,更新apk的操作过两天加上
package com.fsnzzz.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.fsnzzz.bean.ImageUrlBean;
import com.fsnzzz.imp.NetCallBack;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* 同步、异步 GET请求
* 同步、异步POST请求
* 文件、图片上传
* 文件下载
*
*/
public class HttpUtil {
private static HttpUtil instance;
private static OkHttpClient mOkHttpClient;
/**
* Get instance http util.
*
* @return the http util
*/
public static synchronized HttpUtil getInstance() {
if (instance == null) {
synchronized (HttpUtil.class) {
if (instance == null) {
instance = new HttpUtil();
}
}
}
return instance;
}
public HttpUtil() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(30, TimeUnit.SECONDS);//读取超时
builder.connectTimeout(10, TimeUnit.SECONDS);//连接超时
builder.writeTimeout(60, TimeUnit.SECONDS);//写入超时
builder.sslSocketFactory(HttpsTrustManager.createSSLSocketFactory());
builder.hostnameVerifier(new HttpsTrustManager.TrustAllHostnameVerifier());
mOkHttpClient = builder.build();
}
/**
* On async get. 异步GET请求
*
* @param netCallBack the net call back
* @author Fsnzzz
*/
private void onAsyncGET(String url, final NetCallBack netCallBack) {
Request request = new Request.Builder()
.get()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCallBack.onFailure(e.getMessage().toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
netCallBack.onSucceed(response);
}
});
}
/**
* 同步GET请求
*
* @param netCallBack
* @throws IOException
*/
private void onSyncGet(String url,NetCallBack netCallBack) throws IOException {
Request request = new Request.Builder()
.get()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
Response response = call.execute();
netCallBack.onSucceed(response);
}
/**
* 同步POST请求 无 headers
* @param url
* @param bodyParams
* @return
*/
private Response onSyncPOST_Body(String url, Map<String,String> bodyParams) throws IOException {
RequestBody body = getBodyParams(bodyParams);
Request.Builder builder = new Request.Builder();
Request request = builder.post(body)
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
//请求加入调度
Response response = call.execute();
return response;
}
/**
* 同步POST请求 有 headers
* @param url
* @param bodyParams
* @return
*/
private Response onSyncPOST_BodyAndHeader(String url, Map<String,String> bodyParams,Map<String,String> headersParams) throws IOException {
RequestBody body = getBodyParams(bodyParams);
Request.Builder builder = new Request.Builder();
Request request = builder.post(body)
.headers(getRequestHeaders(headersParams))
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
Response response = call.execute();
return response;
}
/**
* 异步post请求 无 headers
* @param url
* @param bodyParams
*/
private void onAsyncPOST_Body(String url,Map<String,String> bodyParams,NetCallBack netCallBack){
Request.Builder builder = new Request.Builder();
Request request = builder.post(getBodyParams(bodyParams))
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCallBack.onFailure(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
netCallBack.onSucceed(response);
}
});
}
/**
* 异步post请求 有 headers
* @param url
* @param bodyParams
*/
private void onAsyncPOST_BodyAndHeaders(String url,Map<String,String> bodyParams,Map<String,String> headersParams,NetCallBack netCallBack){
Request.Builder builder = new Request.Builder();
Request request = builder.post(getBodyParams(bodyParams))
.headers(getRequestHeaders(headersParams))
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCallBack.onFailure(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
netCallBack.onSucceed(response);
}
});
}
/**
* 不带参 图片上传
* @param url
*
* @param data 通过new JSONObject(Map imgs):key->标识 val->图片file路径
* @param netCallBack
*/
public void onUpImage(String url, JSONObject data,NetCallBack netCallBack){
MultipartBody.Builder builder = new MultipartBody.Builder();
if (data != null){
Iterator<String> keys = data.keys();
while (keys.hasNext()){
File file = null;
try {
String key = keys.next();
file = new File(data.getString(key));
builder.addFormDataPart(key, file.getAbsolutePath(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
builder.setType(MultipartBody.FORM);
MultipartBody multipartBody = builder.build();
Request request = new Request.Builder()
.url(url)
.post(multipartBody)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCallBack.onFailure(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
netCallBack.onSucceed(response);
}
});
}
/**
* 异步GET请求
* @param url
* @param netCallBack
* @return
*/
public static void getAsyncGET(String url,NetCallBack netCallBack){
getInstance().onAsyncGET(url,netCallBack);
}
/**
* 同步GET请求
* @param url
* @param netCallBack
* @return
*/
public static void getSyncGET(String url,NetCallBack netCallBack) throws IOException {
getInstance().onSyncGet(url,netCallBack);
}
/**
* 同步POST请求 无 headers
* @param url
* @param bodyParams
* @return
* @throws IOException
*/
public static Response getSyncPOST_Body(String url,Map<String,String> bodyParams) throws IOException {
return getInstance().onSyncPOST_Body(url,bodyParams);
}
/**
* 同步POST请求 有 headers
* @param url
* @param bodyParams
* @return
* @throws IOException
*/
public static Response getSyncPOST_BodyAndHeaders(String url,Map<String,String> bodyParams,Map<String,String> headersParams) throws IOException {
return getInstance().onSyncPOST_BodyAndHeader(url,bodyParams,headersParams);
}
/**
* 设置bodyParams
* @param bodyParams
* @return RequestBody
*/
private RequestBody getBodyParams(Map<String,String> bodyParams){
RequestBody body = null;
FormBody.Builder formBody = new FormBody.Builder();
if (bodyParams != null){
Iterator<String> iterator = bodyParams.keySet().iterator();
String key = "";
while (iterator.hasNext()){
key = iterator.next().toString();
formBody.add(key,bodyParams.get(key));
}
}
return formBody.build();
}
/**
* 异步post 无headers
* @param url
* @param bodyParams
* @param netCallBack
*/
public static void getAsyncPostBody(String url,Map<String,String> bodyParams,NetCallBack netCallBack){
getInstance().onAsyncPOST_Body(url,bodyParams,netCallBack);
}
/**
* 异步post 有headers
* @param url
* @param bodyParams
* @param netCallBack
*/
public static void getAsyncPostBodyHeaders(String url,Map<String,String> bodyParams,Map<String,String> headersParams,NetCallBack netCallBack){
getInstance().onAsyncPOST_BodyAndHeaders(url,bodyParams,headersParams,netCallBack);
}
/**
* 设置
* @param hedersParams
* @return
*/
private Headers getRequestHeaders(Map<String,String> hedersParams){
Headers headers = null;
Headers.Builder builder = new Headers.Builder();
if (hedersParams != null){
Iterator<String> iterator = hedersParams.keySet().iterator();
while (iterator.hasNext()){
String key = iterator.next();
builder.add(key,hedersParams.get(key));
}
}
headers = builder.build();
return headers;
}
/**
* 判断是否联网
* @param context
* @return
*/
public static boolean isNetWorkAvailable(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null){
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()){
if (networkInfo.getState() == NetworkInfo.State.CONNECTED){
return true;
}
}
}
return false;
}
}