首先要引包:
com.squareup.okhttp3:okhttp:3.4.1'
添加权限:
联网,读写权限;
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
代码:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "aaa";
private TextView iv;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 100:{
Bitmap bitmap = (Bitmap) msg.obj;
iv.setBackgroundDrawable(new BitmapDrawable(bitmap));
}break;
case 200:{
String ss= (String) msg.obj;
iv.setText(ss);
}break;
case 300:{
String ss= (String) msg.obj;
iv.setText(ss);
}
case 555:{
Bitmap bitmap= (Bitmap) msg.obj;
iv.setBackgroundDrawable(new BitmapDrawable(bitmap));
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv= (TextView) findViewById(R.id.iv);
}
//下载图片
public void aaa(View view){
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client=new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
//服务器支持缓存的情况下
//添加缓存,没网时也能加载出来
.cache(new Cache(getApplicationContext().getExternalCacheDir(),20*1024*1024))
//服务器不支持缓存情况下我们就需要使用Interceptor来重写Respose的头部信息,从而让okhttp支持缓存。
.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
Response response1 = response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
//cache for 30 days 3600秒,24小时,30天
.header("Cache-Control", "max-age=" + 3600 * 24 * 30)
.build();
return response1;
}
})
.build();
Request request=new Request.Builder()
.url("http://www.ytmfdw.com/image/img2.jpg")
.build();
try {
Response response=client.newCall(request).execute();
if(response.isSuccessful())
{
InputStream inputStream = response.body().byteStream();
Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
Message message=handler.obtainMessage();
message.what=100;
message.obj=bitmap;
handler.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
//下载字符串
public void bbb(View view){
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client=new OkHttpClient.Builder()
.connectTimeout(5,TimeUnit.SECONDS)
//服务器支持缓存的情况下
//添加缓存,没网时也能加载出来
.cache(new Cache(getApplicationContext().getExternalCacheDir(),20*1024*1024))
//服务器不支持缓存情况下我们就需要使用Interceptor来重写Respose的头部信息,从而让okhttp支持缓存。
.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
Response response1 = response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
//cache for 30 days 3600秒,24小时,30天
.header("Cache-Control", "max-age=" + 3600 * 24 * 30)
.build();
return response1;
}
})
.build();
Request request=new Request.Builder()
.url("http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=false&word=%E7%BE%8E%E5%A5%B3%E5%9B%BE%E7%89%87&hs=0&pn=4&spn=0&di=0&pi=20905405197&rn=1&tn=baiduimagedetail&is=0%2C167799&ie=utf-8&oe=utf-8&cl=2&lm=-1&cs=539019579%2C1503243384&os=&simid=&adpicid=0&ln=30&fr=ala&fm=&sme=&cg=girl&bdtype=-1&oriquery=&objurl=http%3A%2F%2Ff.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Fa8014c086e061d9507500dd67ff40ad163d9cacd.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3B4ztp7_z%26e3Bv54AzdH3Flbcn&gsm=")
.build();
try {
Response response=client.newCall(request).execute();
String string = response.body().string();
Message msg=handler.obtainMessage();
msg.what=200;
msg.obj=string;
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
//访问
public void ccc(View view) {
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client=new OkHttpClient.Builder()
.readTimeout(5,TimeUnit.SECONDS)
.connectTimeout(5,TimeUnit.SECONDS)
.build();
FormBody formBody=new FormBody.Builder()
.add("name","woshishazi")
.add("password","1232131")
.build();
Request request=new Request.Builder()
.url("http://10.20.156.55:8080/AndroidTestServer/fileupload")
.method("POST",formBody)
.build();
try {
Response response=client.newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
Message msg=handler.obtainMessage();
msg.what=300;
msg.obj=result;
handler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
//异步任务
public void ddd(View view) {
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client=new OkHttpClient.Builder()
.build();
Request request=new Request.Builder()
.url("http://www.ytmfdw.com/image/img7.jpg")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure() called with: " + "call = [" + call + "], e = [" + e + "]");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()) {
InputStream inputStream = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message message = handler.obtainMessage();
message.what = 555;
message.obj = bitmap;
handler.sendMessage(message);
}else
{
Log.d(TAG, "onResponse: ");
}
}
});
}
}).start();
}
//存储流操作
public void yk(View view) {
/*new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client=new OkHttpClient.Builder()
.connectTimeout(10,TimeUnit.SECONDS)
.build();
Request request=new Request.Builder()
.url("http://www.ytmfdw.com/image/oom.jpg")
.build();
try {
Response respond=client.newCall(request).execute();
if (respond.isSuccessful()){
byte[] bytes = respond.body().bytes();
FileOutputStream fs=new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/"+"My Gril"+".jpg"));
fs.write(bytes,0,bytes.length);
fs.flush();
fs.close();
System.out.print("储存成功");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}*/
new Thread(new Runnable() {
@Override
public void run() {
//配置client
OkHttpClient client = new OkHttpClient.Builder().build();
//配置请求
Request request = new Request.Builder()
.url("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1481169050&di=8a4a00c11254c5972a6cef3c6c516f0b&src=http://h.hiphotos.baidu.com/image/pic/item/dc54564e9258d1093cf78e5cd558ccbf6d814dc3.jpg")
.build();
//client发起请求
try {
Response response = client.newCall(request).execute();
//解析Response
if (response.isSuccessful()) {
byte[] bytes = response.body().bytes();
//流文件操作
FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + File.separator + "hello.jpg"));
fos.write(bytes, 0, bytes.length);
fos.flush();
fos.close();
System.out.println("存储成功!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
//上传文件
public void kkk(View view) {
//配置client
OkHttpClient client = new OkHttpClient.Builder().build();
RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"),new File(Environment.getExternalStorageDirectory()+"/"+"My Gril.jpg"));
// RequestBody fileBody2 = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"),new File(Environment.getExternalStorageDirectory()+"/"+""));
MultipartBody multipartBody = new MultipartBody.Builder()
//上传一张图片
.addPart(new FormBody.Builder().add("name","333333").build())
.addFormDataPart("image","666.jpg", fileBody)
.build();
Request request=new Request.Builder()
.url("http://10.20.156.55:8080/AndroidTestServer/fileupload")
.post(multipartBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.print("onFailure");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Message msg=handler.obtainMessage();
msg.what=300;
msg.obj=result;
handler.sendMessage(msg);
}
});
}
}
布局文件:
<?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.example.okhttp.MainActivity">
<TextView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<Button
android:layout_width="match_parent"
android:text="下载图片"
android:onClick="aaa"
android:layout_margin="2dp"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:text="下载String"
android:onClick="bbb"
android:layout_margin="2dp"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:text="访问"
android:onClick="ccc"
android:layout_margin="2dp"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:text="下载文件"
android:onClick="yk"
android:layout_margin="2dp"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:text="异步任务"
android:onClick="ddd"
android:layout_margin="2dp"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:text="上传文件"
android:onClick="kkk"
android:layout_margin="2dp"
android:layout_height="wrap_content" />
</LinearLayout>
运行结果:

多加了上传文件:
