Android中的网络请求方法有很多。今天主要学学了下OkHttp
的Get
请求、Post
请求。
首先得再gradle build中添加
compile 'com.squareup.okhttp3:okhttp:3.5.0'
然后同步
一、Get请求
OkHttpClient client = new OkHttpClient();//OkHttpClient对象
Request request = new Request.Builder()
.get()
.url("https:www.baidu.com")
.build();//构造Request对象
Call call = client.newCall(request);//将Request封装为Call
Response response = call.execute();//根据需要调用同步或者异步请求方法
//异步调用,并设置回调函数
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(OkHttpActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
contentTv.setText(res);
}
});
}
});
然后 在AndroidManifest.xml中加入联网权限
<uses-permission android:name="android.permission.INTERNET" />
二、Post请求
其实Post和Get差不多的步骤
//与Get步骤类似
OkHttpClient client = new OkHttpClient();
FormBody formBody = new FormBody.Builder()
.add("username", "llh")
.add("password", "llh")
.build();//构建FormBody,传入参数
final Request request = new Request.Builder()
.url("http://www.baidu.com/")
.post(formBody)
.build();
Call call = client.newCall(request);
//调用请求,重写回调方法
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(OkHttpActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
contentTv.setText(res);
}
});
}
});
三、通过Get下载
通过Get请求来下载,主要是在Onresponse方法中,加入File对象获取文件,如下面的获取和下载图片
InputStream in = response.body().byteStream();
int len = 0;
File file = new File(Environment.getExternalStorageDirectory(), "n.png");
FileOutputStream download = new FileOutputStream(file);
byte[] buf = new byte[1024];
while ((len = in.read(buf)) != -1){
fos.write(buf, 0, len);
}
download.flush();
//关闭流
download.close();
in.close();
四、通过Post上传
与下载类似,首先要建立自己的一个file,下面这个代码是指在自己的根目录下寻找自己想上传的文件
Environment.getExternalStorageDirectory()
File file = new File(Environment.getExternalStorageDirectory(), "111.txt");
if (!file.exists()){
Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
}else{
RequestBody requestBody2 = RequestBody.create(MediaType.parse("application/octet-stream"), file);
}
具体其余的一些Get和Post的全部使用方法可以参考https://blog.csdn.net/qq_37381177/article/details/112985344?utm_source=app&app_version=4.9.1&code=app_1562916241&uLinkId=usr1mkqgl919blen