在我们现阶段,okhttp请求框架还是非常流行的。以下是我对get和post两种请求框架的简易实现。
1.okhttp请求框架的get请求
在写代码之前我们应该添加okhtpp的依赖:
compile 'com.squareup.okhttp3:okhttp:3.2.0'
在代码中书写一个方法或者书写一个工具类
先创建okhttp对象
OkHttpClient client=new OkHttpClient();
在创建一个Request对象
Request request = new Request.Builder().url(url).build();
默认的请求方式是get
通过Okhttp的对象生成call对象Call call=client.newCall(request);
通过call来得到结果的返回call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); Message message=new Message(); message.what=1; message.obj=string; handler.sendMessage(message); } }); 2.书写okhtttp请求中的post请求 //创建OkHttpClient OkHttpClient mOkHttpClient = new OkHttpClient(); //封装请求参数FormBody formBody=new FormBody.Builder().add("activity_id",4+"").add("time_id",2927+"").add("child_num",1+"").add("contact","xiallin") .add("mobile","15718812709").add("remark",1+"").build(); 得到Requrest对象Request build = new Request.Builder().url(url).post(formBody).build(); //得到Call对象Call call = client.newCall(build); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); Message ms=new Message(); ms.obj=string; ms.what=1; handler.sendMessage(ms); } });