Okhttp的简单介绍和使用
前言:
通过本篇,可以了解一下几点:
- Android中网络请求进化
- okhttp是什么
- okhttp的简单使用
如果有兴趣,可以看下我的另一篇,okhttp的简单封装:
网络请求发展:
- HttpURLConnection--->Apache HTTP Client--->Volley---->okHttp
OkHttp是什么:
- 项目开源地址 :https://github.com/square/okhttp
- 项目使用:在build.gradle中加入依赖
compile 'com.squareup.okhttp3:okhttp:3.0.1'
OkHttp是一个高效的HTTP库:
- 1.支持 SPDY ,共享同一个Socket来处理同一个服务器的所有请求
- 2.如果SPDY不可用,则通过连接池来减少请求延时
- 3.无缝的支持GZIP来减少数据流量
- 4.缓存响应数据来减少重复的网络请求
优点:
- OkHttp会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。
- 使用 OkHttp 无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果您用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块
Okhttp的基本使用,从以下五方面讲解:
- 1.Get请求(同步和异步)
- 2.POST请求表单(key-value)
- 3.POST请求提交(JSON/String/文件等)(这个有待研究)
- 4.文件下载
- 5.请求超时设置
GET请求同步方法
OkHttpClient client=new OkHttpClient();
Request request = new Request.Builder().url(url) .build();
Response response= client.newCall(request).execute();
String message=response.body().string();
GET请求异步方法
OkHttpClient client=new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
}
});
POST请求提交
在这里解释一下,我在用3.0的时候,去找FormEncodingBuilder(),这个方法,找不到了,就去了他的官网查看了信息,找到了一下一段解释:
- We've replaced the opaque FormEncodingBuilder with the more powerful FormBody and FormBody.Builder combo. Similarly we've upgraded MultipartBuilder into MultipartBody, MultipartBody.Part, and MultipartBody.Builder.
okhttp3.0之前:
OkHttpClient client = new OkHttpClient();
RequestBody forBody = new FormEncodingBuilder().add("username","tom").add("password", "1110").build();
Request request=new Request.Builder().url(url).post(forBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
Log.d("xiaoming",response.body().string());
}
});
okhttp3.0之后
OkHttpClient client = new OkHttpClient();
FormBody formBody = new FormBody.Builder()
.add("type", "1")
.build();
Request request=new Request.Builder().url(url).post(forBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
Log.d("xiaoming",response.body().string());
}
});
文件下载
String url = "http://www.0551fangchan.com/images/keupload/20120917171535_49309.jpg";
//构建request对象
Request request = new Request.Builder().url(url).build();
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = new FileOutputStream(new File("/sdcard/logo.jpg"));
byte[] buffer = new byte[2048];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.flush();
Log.d("wuyinlei", "文件下载成功...");
}
});
超时设置:
okhttp3.0之前:
client.setConnectTimeout(10, TimeUnit.SECONDS);
client.setWriteTimeout(10, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
okhttp3.0之后:
client.newBuilder().connectTimeout(10, TimeUnit.SECONDS);
client.newBuilder().readTimeout(10,TimeUnit.SECONDS);
client.newBuilder().writeTimeout(10,TimeUnit.SECONDS);
下面看下结果演示:
这里写图片描述
注:不知道为什么,我的写入sdcard的权限也加了,就是提示我下载的时候没有权限,我只能用真机了,这里通过log日志来反馈下载成功:
下面来看下代码,布局很简单,四个按钮,一个textview,这里就不解释了
package com.example.okhttpdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button syncGet;
private Button asyncget;
private Button post;
private Button fileDownload,fengzhuang;
private TextView tvtext;
private String result;
private OkHttpClient client;
/**
* 在这里直接设置连接超时,初始化OkHttpClient
*/
private void init() {
client = new OkHttpClient();
client.newBuilder().connectTimeout(10, TimeUnit.SECONDS);
client.newBuilder().readTimeout(10, TimeUnit.SECONDS);
client.newBuilder().writeTimeout(10, TimeUnit.SECONDS);
}
private Request request;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initialize();
initListener();
}
/**
* 事件监听
*/
private void initListener() {
syncGet.setOnClickListener(this);
asyncget.setOnClickListener(this);
post.setOnClickListener(this);
fileDownload.setOnClickListener(this);
fengzhuang.setOnClickListener(this);
}
/**
* 初始化布局控件
*/
private void initialize() {
syncGet = (Button) findViewById(R.id.syncGet);
asyncget = (Button) findViewById(R.id.asyncget);
post = (Button) findViewById(R.id.post);
tvtext = (TextView) findViewById(R.id.tv_text);
fileDownload = (Button) findViewById(R.id.fileDownload);
fengzhuang = (Button) findViewById(R.id.fengzhuang);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.syncGet:
initSyncData();
break;
case R.id.asyncget:
initAsyncGet();
break;
case R.id.post:
initPost();
break;
case R.id.fileDownload:
downLoadFile();
break;
case R.id.fengzhuang:
break;
}
}
/**
* get请求同步方法
*/
private void initSyncData() {
new Thread(new Runnable() {
@Override
public void run() {
try {
request = new Request.Builder().url(Contants.SYNC_URL).build();
Response response = client.newCall(request).execute();
result = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
tvtext.setText(result);
Log.d("MainActivity", "hello");
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
/**
* 异步请求
*/
private void initAsyncGet() {
new Thread(new Runnable() {
@Override
public void run() {
request = new Request.Builder().url(Contants.ASYNC_URL).build();
client.newCall(request).enqueue(new Callback() {
/**
* A call is a request that has been prepared for execution. A call can be canceled. As this object
* represents a single request/response pair (stream), it cannot be executed twice.
*
*
* @param call 是一个接口, 是一个准备好的可以执行的request
* 可以取消,对位一个请求对象,只能单个请求
* @param e
*/
@Override
public void onFailure(Call call, IOException e) {
Log.d("MainActivity", "请求失败");
}
/**
*
* @param call
* @param response 是一个响应请求
* @throws IOException
*/
@Override
public void onResponse(Call call, Response response) throws IOException {
/**
* 通过拿到response这个响应请求,然后通过body().string(),拿到请求到的数据
* 这里最好用string() 而不要用toString()
* toString()每个类都有的,是把对象转换为字符串
* string()是把流转为字符串
*/
result = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
tvtext.setText(result);
}
});
}
});
}
}).start();
}
/**
* 表单提交
*/
private void initPost() {
String url = "http://112.124.22.238:8081/course_api/banner/query";
FormBody formBody = new FormBody.Builder()
.add("type", "1")
.build();
request = new Request.Builder().url(url)
.post(formBody).build();
new Thread(new Runnable() {
@Override
public void run() {
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvtext.setText("提交成功");
}
});
}
});
}
}).start();
}
/**
* 文件下载地址
*/
private void downLoadFile() {
String url = "http://www.0551fangchan.com/images/keupload/20120917171535_49309.jpg";
request = new Request.Builder().url(url).build();
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//把请求成功的response转为字节流
InputStream inputStream = response.body().byteStream();
/**
* 在这里要加上权限 在mainfests文件中
* <uses-permission android:name="android.permission.INTERNET"/>
* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
*/
//在这里用到了文件输出流
FileOutputStream fileOutputStream = new FileOutputStream(new File("/sdcard/logo.jpg"));
//定义一个字节数组
byte[] buffer = new byte[2048];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
//写出到文件
fileOutputStream.write(buffer, 0, len);
}
//关闭输出流
fileOutputStream.flush();
Log.d("wuyinlei", "文件下载成功...");
}
});
}
}
好了,简单的okhttp使用就介绍到这里了,接下来会对其完成以下简单的封装。
由于okhttp3.0较于之前的有些变化,大家使用的时候可以去看下他们官方的说明,这样在使用中就会少了不必要的麻烦了。
网友评论