Okhttp
依赖
implementation ‘com.squareup.okhttp3:okhttp:3.12.1’
get+post请求
get请求
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpClient build = builder.build();
Request.Builder builder1 = new Request.Builder();
builder1.url("");
builder1.get();
Request build1 = builder1.build();
Call call = build.newCall(build1);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(Main2Activity.this,e.getMessage()+"",Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
final String string = body.string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Main2Activity.this,string+"",Toast.LENGTH_SHORT).show();
}
});
}
});
post请求
@Override
public void onClick(View v) {
//TODO 1:client
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpClient client = builder.build();
//TODO 2:request
Request.Builder builder1 = new Request.Builder();
builder1.url("https://www.apiopen.top/login?key=00d91e8e0cca2b76f515926a36db68f5&");
//TODO 2:请求体 RequestBody是抽象类 实现子类 FormBody
//phone=13594347817&passwd=123654
FormBody.Builder builder2 = new FormBody.Builder();
builder2.add("phone", "13594347817");//用户名
builder2.add("passwd", "123654");//密码
FormBody formBody = builder2.build();
builder1.post(formBody);//设置post请求
Request request = builder1.build();
//TODO 3:call:客户端发起请求得到连接
Call call = client.newCall(request);//连接
//TODO 4:reaponse
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(Main2Activity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Toast.makeText(Main2Activity.this, ""+response.body(), Toast.LENGTH_SHORT).show();
}
});
}
OkhttpUtils(工具类)
OkhttpListener
public interface OkHttpListener {
void failur(String str);
void success(String json);
void setMax(int position);
void setCurrent(int position);
}
OkhttpUtils
public class OkhttpUtils {
OkHttpClient okHttpClient;
private OkhttpUtils(){
OkHttpClient.Builder builder = new OkHttpClient.Builder();
okHttpClient = builder.build();
};
private static OkhttpUtils okhttpUtils=null;
public static OkhttpUtils getInstance(){
if(okhttpUtils==null){
synchronized (StringBuilder.class){
if(okhttpUtils==null){
okhttpUtils=new OkhttpUtils();
}
}
}
return okhttpUtils;
}
public void get(String url, final OkHttpListener okHttpListener){
Request builder = new Request.Builder().url(url).get().build();
Call call = okHttpClient.newCall(builder);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
okHttpListener.failur(e.getMessage()+"");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
okHttpListener.success(response.body().string()+"");
}
});
}
public void post(String url, Map<String,String> map,final OkHttpListener okHttpListener){
FormBody.Builder builder = new FormBody.Builder();
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry:entries
) {
String key = entry.getKey();
String value = entry.getValue();
builder.add(key,value);
}
FormBody build = builder.build();
Request builder1 = new Request.Builder().url(url).post(build).build();
Call call = okHttpClient.newCall(builder1);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
okHttpListener.failur(e.getMessage()+"");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
okHttpListener.success(response.body().string()+"");
}
});
}
public void download(String str , final String path, final OkHttpListener okHttpListener){
Request builder = new Request.Builder()
.url(str)
.get()
.build();
Call call = okHttpClient.newCall(builder);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
okHttpListener.failur(e.getMessage()+"");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
long max = body.contentLength();
okHttpListener.setMax((int) max);
InputStream inputStream = body.byteStream();
FileOutputStream fileOutputStream = new FileOutputStream(path);
int len=0;
byte[] bytes=new byte[1024];
int count=0;
while ((len=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
count+=len;
okHttpListener.setCurrent(count);
}
okHttpListener.success(response.body()+"");
}
});
}
public void upload(final String str,String servername, String type, String path, final OkHttpListener okHttpListener){
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
builder.addFormDataPart("file",servername,RequestBody.create(MediaType.parse(type),new File(path)));
MultipartBody build = builder.build();
final Request request = new Request.Builder().url(str).post(build).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
okHttpListener.failur(e.getMessage()+"");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
okHttpListener.success(string+"");
}
});
}
}
Log拦截器打印(Interceptor)
private OkhttpUtils(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.e("########",message+"");
}
});
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request build = chain.request().newBuilder().header("token", "day3okhttp").build();
return chain.proceed(build);
}
};
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//log拦截器一定在token之前
builder.addInterceptor(httpLoggingInterceptor);
builder.addInterceptor(interceptor);
okHttpClient = builder.build();
};
private static OkhttpUtils okhttpUtils=null;
public static OkhttpUtils getInstance(){
if(okhttpUtils==null){
synchronized (StringBuilder.class){
if(okhttpUtils==null){
okhttpUtils=new OkhttpUtils();
}
}
}
return okhttpUtils;
}