一、引言
- 描述:如果app需要和服务器进行数据交互。那么okHttp这一套处理HTTP网络请求的依赖库,就是非常不错的选择,在Android开发中,我估计大部分软件都在使用他进行网络请求连接和数据交互。因为使用方便,jar包“轻携”,对于初学者来说还是非常友好的,技术刚起步,没有自己封装网络连接包的能力前非常适合使用。
- 难度:初级
- 优势:
1、HTTP/2 支持允许对同一主机的所有请求共享一个套接字。
2、连接池可减少请求延迟(如果 HTTP/2 不可用)。
3、透明 GZIP 可缩小下载大小。
4、响应缓存完全避免了重复请求的网络。
二、编码
1、权限配置
使用okHttp进行网络交互,肯定绕不开网络权限。在AndroidManifest.xml文件里就需要添加如下代码。
<uses-permission android:name="android.permission.INTERNET" />
2、依赖
关于客户端和服务端的数据交互,用的比较熟练的就是okHttp和Gson的组合。okHttp负责交互数据,Gson则负责数据处理(对数据进行转换)。
//okHttp
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
//gson Json -> Object
implementation 'com.google.code.gson:gson:2.8.2'
3、使用
(1)okHttp
OkHttp 适用于 Android 5.0+(API 级别 21+)和 Java 8+。
OkHttp 依赖于 Okio 实现高性能 I/O 和 Kotlin 标准库。两者都是具有强大向后兼容性的小型库。
强烈建议保持 OkHttp 最新。与自动更新 Web 浏览器一样,保持最新状态 使用 HTTPS 客户端是针对潜在安全问题的重要防御措施。
private static String IP = "10.0.2.2";
private static String port = "8080";
private static String p = "http://" + IP + ":" + port + "/"; //服务器接收地址
/**
* 使用静态内部类的方式实现单例模式
*/
private static class UploadUtilInstance{
private static final okHttp INSTANCE = new okHttp();
}
/**
* post方法
* @param key controller层的@PostMapper("")
* @param body 传递的数据
* @return 返回数据 @type String
* @throws IOException
*/
public static String post(String key, RequestBody body) throws IOException {
//拼接完整的url
String path = p + key;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(path)
.post(body)
// token验证,也可以使用BirdgeInterceptor拦截器进行设置
// .header("token", user.getString("token", ""))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response); // 一般都是返回401、404一些异常,可以自己定义方法进行处理
String resp = response.body().string();
return resp;
}
/**
* get方法
* @param key controller层的@PostMapper("")
* @return 返回数据 @type String
* @throws IOException
*/
public static String get(String key) throws IOException {
//拼接完整的url
String path = p + key;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(path)
.get()
// token验证,也可以使用BirdgeInterceptor拦截器进行设置
// .header("token", user.getString("token", ""))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
return response.body().string();
}
/**
* 接收Image资源
* @param type 设置的静态资源映射地址 registry.addResourceHandler("/image/**").addResourceLocations("file:D://image");
* @param path 图片名
* @return 返回数据 @type String
* @throws IOException
*/
public static BitmapDrawable getBitmap(String type, String path) throws IOException{
URL url = new URL(p + type + path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream outStream =new ByteArrayOutputStream();
byte[] buffer = new byte[9999];
int len = 0;
while ((len = inputStream.read(buffer)) != -1)//读取流中的数据
{
outStream.write(buffer,0,len);
}
inputStream.close();
//得到的字节Byte
byte[] b = outStream.toByteArray();
Bitmap map = BitmapFactory.decodeByteArray(b,0,b.length);
BitmapDrawable bd = new BitmapDrawable(map);
return bd;
}
return null;
}
(2)Gosn
将服务器传了的关于User实体的json格式数据转换为实体数据。用来在Java对象和JSON数据之间进行映射的Java类库。可以将一个Json字符转成一个Java对象,或者将一个Java转化为Json字符串
一般传过来都是Result数据,这里为了方便理解,就用User来说明
new Thread(new Runnable() {
@Override
public void run() {
try {
String getJson = okHttp.get("info");
if (getJson == null) {
Gson gson = new Gson();
// 将服务器传了的关于User实体的json格式数据转换为实体数据
// 一般传过来都是Result<User>数据,这里为了方便理解,就用User来说明
User user = gson.fromJson(getJson, new TypeToken<User>(){}.getType());
} else {
// 反馈结果
Looper.prepare();
// result.getMsg()
Toast.makeText(this, "结果为空!", Toast.LENGTH_SHORT).show();
Looper.loop();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();