第一步:添加依赖
compile 'com.squareup.okhttp3:okhttp:3.9.0'
第二步:创建功能类
package com.example.mabiao.okhttpmode.jiekou;
import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by mabiao on 2017/9/20.
*/
public class OKhttp {
private Dir dir;
private Request request;
public void Call(String url, MeiJu m, Map<String,String> map){
//创建okhttp对象
OkHttpClient mOkhttpclient=new OkHttpClient();
if(m==MeiJu.GET){
//如果是get请求
String urls=url+"?";
for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
urls+=stringStringEntry.getKey()+"="+stringStringEntry.getValue()+"&&";
}
//创建一个Request
request = new Request.Builder()
.url(urls)
.get()
.build();
}else if(m==MeiJu.POST){
//如果是post
FormBody.Builder form=new FormBody.Builder();
//设置请求参数
for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
form.add(stringStringEntry.getKey(),stringStringEntry.getValue());
}
//请求体
RequestBody body=form.build();
request=new Request.Builder()
.post(body)
.url(url)
.build();
}
//new Call
Call call=mOkhttpclient.newCall(request);
//请求调度
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
dir.onFailure(call,e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
dir.onResponse(call,response);
}
});
}
public void setDir(Dir dir) {
this.dir = dir;
}
}
第三步创建接口
public interface Dir {
//回调方法
void onFailure(Call call, IOException e);
void onResponse(Call call, Response response);
}
第四步:创建枚举类
public enum MeiJu {
GET,或POST 类型
GET,POST
}
第五步在MainActivity中调用
public class MainActivity extends AppCompatActivity implements Dir {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
}
private void initData() {
//回调过来的功能类
OKhttp oh=new OKhttp();
//接口回调
oh.setDir(this);
//key值,如果为空可以不写直接new一个空的map
Map<String,String> map=new HashMap<>();
//调用方法
oh.Call(NewsAPK.NEWSURL, MeiJu.GET,map);
}
//接口回调回来的数据
@Override
public void onFailure(Call call, IOException e) {
}
//接口返回来的数据
@Override
public void onResponse(Call call, Response response) {
//返回来的数据在这里调用解析
System.out.println("+++++++++++++++++++++++++++++"+response);
}
}