一:OkHttp简介与由来
现在android网络方面的第三方库很多,volley,Retrofit,OKHttp等,各有各自的特点,OKHttp是一款高效的HTTP客户端,支持连接同一地址的链接共享同一个socket,通过连接池来减小响应延迟,还有透明的GZIP压缩,请求缓存等优势,所以我们更有理由相信OkHttp的强大
二:使用前导入依赖
compile 'com.squareup.okhttp3:okhttp:3.9.0'
1:首先介绍get请求方式
//1:创建OkHttpClient对象,两种任选一种
//OkHttpClient client = new OkHttpClient();
OkHttpClient client = new OkHttpClient.Builder()
//.addInterceptor(new 类())//添加一个拦截器
.build();
//传入参数的方式有多种
//1:.addHeader("name","value");
//2:header是覆盖
//3:创建headers
// Headers headers = new Headers.Builder()
// .add("name","value")
// .add("name","value")
// .build();
//2:创建Request对象
final Request request = new Request.Builder()
//.addHeader("mobile","999")//第一种
//.addHeader("password","000")//第一种
//.header("name","value")//第二种
//.headers(headers)//第三种
.get()//使用get方式请求
.url("http://www.wuxirui.com")//地址
.build();
//3:创建Call对象
Call call = client.newCall(request);
//4:请求网络,请求网络分为两种异步与同步请求 enqueue方法是异步请求
call.enqueue(new Callback() {
//请求失败
@Override
public void onFailure(Call call, IOException e) {
}
//请求成功
@Override
public void onResponse(Call call, Response response) throws IOException {
//response.body().string()本质上是读流的操作
final String res = response.body().string();
Log.i(TAG,res);
/*获取到数据之后把数据展示到ui上,因为请求网络是在子线程,更新ui需要在主
线程中进行,可以用Handler,runOnUiThread等方法,这里用runOnUiThread方法,
下面post方式请求的时候再用Hnadler*/
runOnUiThread(new Runnable() {
@Override
public void run() {
show.setText(res);
}
});
}
});
}
//1:创建OkHttpClient对象,两种任选一种
//OkHttpClient client = new OkHttpClient.Builder().build();
OkHttpClient client = new OkHttpClient();
//2:提供post请求需要的body对象
FormBody body = new FormBody.Builder()
.add("mobile", "***********")
.add("password", "******")
.build();
//3:创建Request对象
Request request = new Request.Builder()
.post(body)
.url("http://120.27.23.105/user/login")
.build();
//4:创建Call对象
Call call = client.newCall(request);
//5:请求网络,请求网络分为两种异步与同步请求 enqueue方法是异步请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//response.body().string()本质上是读流的操作
String res = response.body().string();
//handler发送消息改变Ui
Message message = handler.obtainMessage();
message.what=1;
message.obj=res;
message.sendToTarget();
}
});
handler代码
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==1){
String s = (String) msg.obj;
show.setText(s);
}
}
};
package com.okhttp;
import android.os.Handler;
import android.os.Message;
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 java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity{
private TextView show;
public static final String TAG = "MainActivity";
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==1){
String s = (String) msg.obj;
show.setText(s);
}
}
};
private Button tb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (TextView)findViewById(R.id.show);
tb = (Button)findViewById(R.id.tb);
tb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//因为是同步请求操作,所以要放到子线程中
new Thread(new Runnable() {
@Override
public void run() {
//1:创建OkHttpClient对象
OkHttpClient client = new OkHttpClient();
//2:创建Request对象
final Request request = new Request.Builder()
.get()//使用get方式请求
.url("http://www.*******.com")//地址
.build();
//3:创建Call对象
Call call = client.newCall(request);
//4:请求网络,请求网络分为两种异步与同步请求 execute是同步
try {
Response execute = call.execute();
String string = execute.body().string();
//handler发送消息改变Ui
Message message = handler.obtainMessage();
message.what=1;
message.obj=string;
message.sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
}