OkHttp学习笔记
程序员文章站
2022-07-13 10:55:12
...
1、为什么使用Okhttp?
以前google推荐使用Volley框架,Volley封装了HttpClient,但是Android6.0之后废弃HTTPClient相关属性导致Volley不能使用(可以将HTTPClient做Library导入解决此问题)。具体Volley代码展示:
OkHttp可以是可以解决此问题的一个很好的框架。
2、使用代码
package com.example.okhttpdemo;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.okhttpdemo.R;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btn(View v) throws IOException {
switch (v.getId()) {
case R.id.btnGet:
doGet();
break;
case R.id.btnPost:
doPost();
break;
case R.id.btnPostString:
doPostString();
break;
case R.id.btnDown:
doDownLoad();
break;
}
}
@SuppressLint("HandlerLeak")
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Toast.makeText(MainActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
}
};
OkHttpClient okHttpClient = new OkHttpClient();
private void doGet() throws IOException {
//1、拿到OkHttpClient对象
// OkHttpClient okHttpClient = new OkHttpClient();
//2、构造Request
Request.Builder builder = new Request.Builder();
Request build = builder.get().url("https://www.baidu.com/").build();
exeRequest(build);
}
private void exeRequest(Request build) {
//3、将Request封装成Call
Call call = okHttpClient.newCall(build);
//4、执行Call
// Response response = call.execute();//同步
call.enqueue(new Callback() {//异步
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
Log.i("aa", Thread.currentThread().toString());
Message message=Message.obtain();
message.obj=response.body().toString();
handler.sendMessage(message);
}
});
}
/**
* 正常post请求
*/
private void doPost() {
Request.Builder builder=new Request.Builder();
FormBody formBody=new FormBody.Builder().add("key1","value1").build();
Request build = builder.url("").post(formBody).build();
exeRequest(build);
}
/**
* post一个字符串
*/
private void doPostString() {
RequestBody requestBody=RequestBody.create(MediaType.parse("text/plain,chaset=utf-8"),"aaaa");
Request.Builder builder=new Request.Builder();
Request build = builder.url("").post(requestBody).build();
exeRequest(build);
}
/**
* post一个File
*/
private void doPostFile() {
File file=null;
RequestBody requestBody=RequestBody.create(MediaType.parse("application/octet-stream"),file);
Request.Builder builder=new Request.Builder();
Request build = builder.url("").post(requestBody).build();
exeRequest(build);
}
/**
* post一个File+其他参数
*/
private void doPostFileAndOther() {
File file=null;
RequestBody requestBody=RequestBody.create(MediaType.parse("application/octet-stream"),file);
MultipartBody.Builder multipartBody=new MultipartBody.Builder();
MultipartBody build1 = multipartBody.setType(MultipartBody.FORM).addFormDataPart("", "").addPart(requestBody).build();
Request.Builder builder=new Request.Builder();
Request build = builder.url("").post(build1).build();
exeRequest(build);
}
/**
* 下载文件
*/
private void doDownLoad() {
Request.Builder builder = new Request.Builder();
Request build = builder.get().url("https://wx4.sinaimg.cn/mw690/8f4241dbly1fs1i0y9613j23402c0qkq.jpg").build();
//3、将Request封装成Call
Call call = okHttpClient.newCall(build);
//4、执行Call
// Response response = call.execute();//同步
call.enqueue(new Callback() {//异步
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
File file=new File(Environment.getExternalStorageDirectory()+"/zz.jpg");
InputStream inputStream = response.body().byteStream();
int len=0;
byte[]bytes=new byte[128];
FileOutputStream fileOutputStream=new FileOutputStream(file);
while ((len=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
}
});
}
}
上一篇: ClickHouse 表引擎