OkHttp的基本使用
2016-08-07 01:25
357 查看
OkHttp的使用要比volley强大的多,他可以处理文件的上传和下载 ,而volley就做不到这么灵活, 并且在默认情况下会在数据请求的时候将数据进行压缩,这样有效的降低数据传输的大小 , 也支持想volley一样 的网络缓存的功能,当网络出现问题时,自动重试一个主机的多个 IP 地址
okHttp使用步骤:
1. 获取okHttpClient实例 2. 构建Request(Request是OkHttp中访问的请求, Builder是辅助类,可选:是否传参) 3. 获取网络请求(Call) 4. 执行网络请求(同步excute or 异步enqueue) 5. 获取Response(Response即OkHttp中的响应)
前期准备工作:
okhttp 的jar包下载地址:(http://u.download.csdn.net/upload/success)
然后将网络权限添加到清单文件中
<uses-permission android:name="android.permission.INTERNET" />
**接下来我们先看布局文件**
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.alpha.demookhttp.MainActivity"> <Button android:id="@+id/btn_get" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Get" /> <Button android:id="@+id/btn_post" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="POST" /> <TextView android:id="@+id/tv_OK" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="#0f0" /> <TextView android:id="@+id/tv_error" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="#f00" /> </LinearLayout>
代码实现
package com.okhttp; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.io.IOException; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; public class MainActivity extends AppCompatActivity { public static final String URL_GET = "http://apis.juhe.cn/mobile/get?phone=13888888888&key=daf8fa858c330b22e342c882bcbac622"; public static final String URL_POST = "http://apis.juhe.cn/mobile/get "; @Bind(R.id.btn_get) Button btnGet; @Bind(R.id.btn_post) Button btnPost; @Bind(R.id.tv_OK) TextView tvOK; @Bind(R.id.tv_error) TextView tvError; private OkHttpClient client; //定义一个handler 为了给文本显示内容 private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: String error = (String) msg.obj; tvError.setText(error); break; case 1: String result = (String) msg.obj; tvOK.setText(result); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); //创建 httpclint 因为任何一个请求都需要用,所以直接定义成全局的 client = new OkHttpClient(); } @OnClick({R.id.btn_get, R.id.btn_post}) public void onClick(View view) { switch (view.getId()) { case R.id.btn_get: //任何一个网络框架如果不去特意指定请求的方式的话默认都是get方式 //默认情况下Request就是使用GET方式,所以不需要指定请求的方式 Request get_request = new Request.Builder() .url(URL_GET)// 指定请求的地址 .build(); // 同步执行网络请求. //这么写就是在主线程里面进行操作 ,是不可以的 // client.newCall(get_request).execute() // 异步执行网络请求 //由于是异步的请求,所以不能直接在成功或失败的方法里面设置要显示的文本 client.newCall(get_request).enqueue(new Callback() { //失败的方法 @Override public void onFailure(Call call, IOException e) { Message msg = new Message(); msg.what = 0; msg.obj = e.toString(); handler.sendMessage(msg); } //成功的方法 @Override public void onResponse(Call call, Response response) throws IOException { //成功的方法里面的内容都封装在了 body 里面 类型是ResponseBody //而显示文本不能直接将ResponseBody设置为文本视图中 ResponseBody body = response.body(); // 所以要把返回的结果转换为String类型 String string = body.string(); //body 还有其他两个方法 // byte[] bytes = body.bytes();// 把返回的结果转换为byte数组 // InputStream inputStream = body.byteStream();// 把返回的结果转换为流 Message msg = new Message(); msg.what = 1; msg.obj = string; handler.sendMessage(msg); } }); break; case R.id.btn_post: //post的请求跟get基本类似 , 只有在请求的时候有些区别, //在请求时候报吧参数添加进去 RequestBody body = new FormBody.Builder() .add("phone", "13888888888")// 构造请求的参数 .add("key", "daf8fa858c330b22e342c882bcbac622")// 构造请求的参数 .build(); Request post_request = new Request.Builder() .url(URL_POST)// 指定请求的地址 .post(body)// 指定请求的方式为POST .build(); client.newCall(post_request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Message msg = new Message(); msg.what = 0; msg.obj = e.toString(); handler.sendMessage(msg); } @Override public void onResponse(Call call, Response response) throws IOException { ResponseBody body = response.body(); String string = body.string();// 把返回的结果转换为String类型 Message msg = new Message(); msg.what = 1; msg.obj = string; handler.sendMessage(msg); } }); break; } } }
上面就是 okhttp的基本使用,
还有一些第三方的库将okhttp的使用又进行了封装,使用起来就更加的方便简单了
需要导入的jar包:
http://download.csdn.net/detail/q9104422999/9597293
package com.okhttpsutils; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import okhttp3.Call; public class MainActivity extends AppCompatActivity { public static final String URL_GET = "http://apis.juhe.cn/mobile/get?phone=13888888888&key=daf8fa858c330b22e342c882bcbac622"; public static final String URL_POST = "http://apis.juhe.cn/mobile/get "; @Bind(R.id.btn_get) Button btnGet; @Bind(R.id.btn_post) Button btnPost; @Bind(R.id.tv_OK) TextView tvOK; @Bind(R.id.tv_error) TextView tvError; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } @OnClick({R.id.btn_get, R.id.btn_post}) public void onClick(View view) { switch (view.getId()) { case R.id.btn_get: OkHttpUtils.get().url(URL_GET).build().execute(new StringCallback() { @Override public void onError(Call call, Exception e) { tvError.setText(e.toString()); } @Override public void onResponse(String response) { tvOK.setText(response); } }); break; case R.id.btn_post: OkHttpUtils.post().url(URL_POST).addParams("phone", "13888888888").addParams("key", "daf8fa858c330b22e342c882bcbac622").build().execute(new StringCallback() { @Override public void onError(Call call, Exception e) { tvError.setText(e.toString()); } @Override public void onResponse(String response) { tvOK.setText(response); } }); break; } } }
相关文章推荐
- OkHttp使用(一)基本使用
- Android okhttp3的基本使用
- OkHttp使用(一)基本使用
- OkHttp基本使用
- android Okhttp3的基本使用
- OkHttp,Retrofit 1.x - 2.x 基本使用
- OkHttp3.0的基本使用
- OkHttp基本使用(五)拦截器
- OkHttp基本使用(四)缓存
- Retrofit+Rxjava+okhttp基本使用
- OkHttp的基本使用——替代Apache HttpClient
- Retrofit+okhttp基本使用
- OkHttp,Retrofit 1.x - 2.x 基本使用
- Android中Okhttp进行get和post提交及数据请求的基本使用
- OKHttp的基本使用和简单封装
- OKHttp的基本使用
- OKHttp基本使用
- okhttp框架的最简单的基本使用 post和get请求以及用gson解析请求的数据
- OkHttp使用(一)基本使用
- OkHttp基本使用