OkHttp入门学习
参考教程:
https://www.baeldung.com/guide-to-okhttp
https://zhuanlan.zhihu.com/p/337000646
依赖引入
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
get同步请求与异步请求
package com.mrs.main;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.IOException;
/**
* description: GetDemo
* date: 2022/9/7 18:56
* author: MR.孙
*/
@Slf4j
public class GetDemo {
public static void main(String[] args) {
//使用 OkHttp 同步 GET
synchronization();
//使用OkHttp 异步请求GET
asynchronous();
}
/**
* @description: 异步请求GET
* @return: void
* @author: MR.孙
* @date: 2022/9/7 19:14
*/
private static void asynchronous() {
//1.创建OkHttpClient对象
OkHttpClient client = new OkHttpClient();
//2.设置请求
Request request = new Request.Builder()
.url("https://www.baidu.com")
.build();
//3.封装call
Call call = client.newCall(request);
//4.异步调用,并设置回调函数
call.enqueue(new Callback() {
public void onFailure(Call call, IOException e) {
log.info("异步get请求发送失败");
}
public void onResponse(Call call, Response response) throws IOException {
if(response!=null && response.isSuccessful()){
log.info("异步get请求发送成功");
}
}
});
}
/**
* @description: 同步get请求
* @return: void
* @author: MR.孙
* @date: 2022/9/7 19:12
*/
private static void synchronization() {
//1.创建okHttp对象
OkHttpClient client = new OkHttpClient();
//2.设置请求
Request request = new Request.Builder()
.url("https://www.baidu.com")
.build();
//3.封装call
Call call = client.newCall(request);
try {
Response execute = call.execute();
System.out.println(execute.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
post同步请求和异步请求
form形式和json参数形式
package com.mrs.main;
import com.alibaba.fastjson.JSON;
import com.mrs.entity.User;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.IOException;
/**
* description: PostDemo
* date: 2022/9/7 22:31
* author: MR.孙
*/
@Slf4j
public class PostDemo {
public static void main(String[] args) {
//Post异步请求请求 form表单形式
getsysn("https://www.wanandroid.com/user/login");
//Post异步请求请求 form表单形式
getAsyn("https://www.wanandroid.com/user/login");
// json参数形式
User user = new User();
user.setUsername("slzgg666");
user.setPassword("123456");
String json = JSON.toJSONString(user);
// System.out.println(json);
// {"password":"123456","username":"slzgg666"}
getJsonParams("https://www.wanandroid.com/user/login",json);
}
private static void getJsonParams(String url,String json) {
//创建OkHttpClient
OkHttpClient client = new OkHttpClient();
//构建参数
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
//构建request
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
//将request封装成Call
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
log.info("发送表单数据失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response !=null && response.isSuccessful()){
log.info("响应体内容为:->{}", response.body().string());
}
}
});
}
private static void getsysn(String url) {
//创建OkHttpClient对象
OkHttpClient client = new OkHttpClient();
//创建FormBody对象构建参数
FormBody formBody = new FormBody.Builder()
.add("username", "slzgg666")
.add("password", "123456")
.build();
//构建request
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
//封装Call
Call call = client.newCall(request);
try {
Response response = call.execute();
log.info("响应体内容为:->{}",response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
private static void getAsyn(String url) {
//创建OkHttpClient对象
OkHttpClient client = new OkHttpClient();
//构建参数
FormBody formBody = new FormBody.Builder()
.add("username", "slzgg666")
.add("password", "123456")
.build();
//构建 request
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
//封装Call
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
log.info("发送表单数据失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response!=null && response.isSuccessful()){
log.info("响应体内容为:->{}", response.body().string());
}
}
});
}
}
文件上传
package com.mrs.main;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.*;
/**
* description: DownloadDemo
* date: 2022/9/7 23:32
* author: MR.孙
*/
@Slf4j
public class DownloadDemo {
public static void main(String[] args) {
//文件下载
download("https://img2.baidu.com/it/u=4216378944,3643750935&fm=253&fmt=auto&app=120&f=JPEG?w=1600&h=683"
,"D:\\file\\","img1.jpg");
}
private static void download(String url, String target, String fileName) {
//1.获取okHttpClient对象
OkHttpClient client = new OkHttpClient();
//2.构建request
Request request = new Request.Builder()
.url(url)
.build();
//3.异步调用
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
//4.文件下载
downloadFile(response,target,fileName);
}
}
});
}
private static void downloadFile(Response response, String target, String fileName) {
InputStream inputStream = null;
byte[] buf = new byte[1024*1024*1024];
int len = 0;
FileOutputStream outputStream = null;
inputStream = response.body().byteStream();
//文件大小
long total = response.body().contentLength();
System.out.println(total);
File file = new File(target + fileName);
try {
outputStream = new FileOutputStream(file);
while((len=inputStream.read(buf))!=-1){
outputStream.write(buf,0,len);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(inputStream!=null) inputStream.close();
if(outputStream!=null) outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

浙公网安备 33010602011771号