1聂儒,導(dǎo)入依賴包:
compile 'com.squareup.okhttp3:okhttp:3.8.1'
2,在manifest中添加:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
3,代碼如下:
import android.util.Log;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by fyc on 2017/7/12.
*/
public class OkHttpUtil {
public final static int READ_TIMEOUT = 100;
public final static int CONNECT_TIMEOUT = 60;
public final static int WRITE_TIMEOUT = 60;
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final byte[] LOCKER = new byte[0];
private static OkHttpUtil mInstance;
private OkHttpClient mOkHttpClient;
/**
* 自定義網(wǎng)絡(luò)回調(diào)接口
*/
public interface NetCall {
void success(Call call, Response response) throws IOException;
void failed(Call call, IOException e);
}
private OkHttpUtil() {
okhttp3.OkHttpClient.Builder ClientBuilder = new okhttp3.OkHttpClient.Builder();
ClientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);//讀取超時
ClientBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);//連接超時
ClientBuilder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);//寫入超時
//支持HTTPS請求硫痰,跳過證書驗(yàn)證
ClientBuilder.sslSocketFactory(createSSLSocketFactory());
ClientBuilder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
mOkHttpClient = ClientBuilder.build();
}
/**
* 單例模式獲取OkHttpUtil
*
* @return
*/
public static OkHttpUtil getInstance() {
if (mInstance == null) {
synchronized (LOCKER) {
if (mInstance == null) {
mInstance = new OkHttpUtil();
}
}
}
return mInstance;
}
/**
* get請求衩婚,同步方式,獲取網(wǎng)絡(luò)數(shù)據(jù)效斑,是在主線程中執(zhí)行的非春,需要新起線程,將其放到子線程中執(zhí)行
*
* @param url
* @return
*/
public Response getData(String url) {
//1 構(gòu)造Request
Request.Builder builder = new Request.Builder();
Request request = builder.get().url(url).build();
//2 將Request封裝為Call
Call call = mOkHttpClient.newCall(request);
//3 執(zhí)行Call,得到response
Response response = null;
try {
response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* post請求奇昙,同步方式护侮,提交數(shù)據(jù),是在主線程中執(zhí)行的储耐,需要新起線程羊初,將其放到子線程中執(zhí)行
*
* @param url
* @param bodyParams
* @return
*/
public Response postData(String url, Map<String, String> bodyParams) {
//1構(gòu)造RequestBody
RequestBody body = setRequestBody(bodyParams);
//2 構(gòu)造Request
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.post(body).url(url).build();
//3 將Request封裝為Call
Call call = mOkHttpClient.newCall(request);
//4 執(zhí)行Call,得到response
Response response = null;
try {
response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* get請求什湘,異步方式长赞,獲取網(wǎng)絡(luò)數(shù)據(jù),是在子線程中執(zhí)行的闽撤,需要切換到主線程才能更新UI
*
* @param url
* @param netCall
* @return
*/
public void getDataAsyn(String url, final NetCall netCall) {
//1 構(gòu)造Request
Request.Builder builder = new Request.Builder();
Request request = builder.get().url(url).build();
//2 將Request封裝為Call
Call call = mOkHttpClient.newCall(request);
//3 執(zhí)行Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCall.failed(call, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
netCall.success(call, response);
}
});
}
/**
* post請求得哆,異步方式,提交數(shù)據(jù)哟旗,是在子線程中執(zhí)行的贩据,需要切換到主線程才能更新UI
*
* @param url
* @param bodyParams
* @param netCall
*/
public void postDataAsyn(String url, Map<String, String> bodyParams, final NetCall netCall) {
//1構(gòu)造RequestBody
RequestBody body = setRequestBody(bodyParams);
//2 構(gòu)造Request
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.post(body).url(url).build();
//3 將Request封裝為Call
Call call = mOkHttpClient.newCall(request);
//4 執(zhí)行Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCall.failed(call, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
netCall.success(call, response);
}
});
}
/**
* post的請求參數(shù),構(gòu)造RequestBody
*
* @param BodyParams
* @return
*/
private RequestBody setRequestBody(Map<String, String> BodyParams) {
RequestBody body = null;
okhttp3.FormBody.Builder formEncodingBuilder = new okhttp3.FormBody.Builder();
if (BodyParams != null) {
Iterator<String> iterator = BodyParams.keySet().iterator();
String key = "";
while (iterator.hasNext()) {
key = iterator.next().toString();
formEncodingBuilder.add(key, BodyParams.get(key));
Log.d("post http", "post_Params===" + key + "====" + BodyParams.get(key));
}
}
body = formEncodingBuilder.build();
return body;
}
/**
* 生成安全套接字工廠闸餐,用于https請求的證書跳過
*
* @return
*/
private SSLSocketFactory createSSLSocketFactory() {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
}
return ssfFactory;
}
public String postJson(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = mOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
public void postJsonAsyn(String url, String json, final NetCall netCall) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
//2 構(gòu)造Request
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.post(body).url(url).build();
//3 將Request封裝為Call
Call call = mOkHttpClient.newCall(request);
//4 執(zhí)行Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCall.failed(call, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
netCall.success(call, response);
}
});
}
/**
* 用于信任所有證書
*/
class TrustAllCerts implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}
okhttp3簡單封裝GET和POST請求工具類
android 中okhttp post請求傳遞json數(shù)據(jù)