一.准备工作
在dependencies中添加依赖
compile'com.squareup.okhttp3:okhttp:3.2.0'
在配置文件AndroidManifest.xml中添加网络访问权限以及读取本地文件的权限
<uses-permission android:name="android.permission.INTERNET" /><!-- 网络访问权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <!-- sdcard读权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!-- sdcard写权限 -->
二.完成okhttp3请求的代码封装
首先我们分析一般请求的可能性
- 1.无参数的get请求
- 2.有参数的post请求
- 3.上传文件的post请求
- 4.下载文件的请求
大概步骤
- 1.建立一个OkhttpClient 连接 eg:OkHttpClient client=new OkHttpClient();//建立一个连接
- 2.要是需要进行request的body 就需要进行 对实体的添加请求的参数。eg:RequestBody rbody=RequestBody.create(CONTENT_TYPE,getParams(params).getBytes());
- 3.建立请求实体 request eg: Request request =new Request.Builder().url(url).build();
- 4..响应的接收Response 的操作 eg:Response response = client.newCall(request).execute()
- 5.返回结果body eg:body.string();
- 6.还有一些其他的比如Builder类 Header类等等。
1.无参get请求/和有参数的post
/**
* @param url 请求地址
* @param params 参数(有参数输入参数)(无参数输入null)
* @return
*/
public static String postHtml(String url, Map<String, Object> params) {
//链接的建立
OkHttpClient client = new OkHttpClient();
//请求的设置
Request.Builder builder = new Request.Builder().url(url);
//请求体的制作
if (!params.isEmpty() && params != null) {
RequestBody requestBody = RequestBody.create(CONTENT_TYPE, parseParams(params).getBytes());
builder.post(requestBody);
}
Request request = builder.build();
//响应的接收
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("请求失败 " + response);
}
ResponseBody responseBody = response.body();
return responseBody.string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
请求的入参的合并成byte格式
/**
* 参数的合并
*
* @param params
* @return
*/
private static String parseParams(Map<String, Object> params) {
Iterator<String> iterator = params.keySet().iterator();
StringBuilder builder = new StringBuilder();
while (iterator.hasNext()) {
String key = iterator.next();
String value = (String) params.get(key);
try {
builder.append("&").append(key).append("=").append(URLEncoder.encode(value, "utf8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
if (builder.length() > 1) {
return builder.substring(1).toString();
} else {
return builder.toString();
}
}
2.上传图片
/**
*
* @param url 请求地址
* @param params 参数(有参数输入参数)(无参数输入null)
* @param filePaths 图片地址(有参数输入参数)
* @return
*/
public static String postFiles(String url, Map<String, Object> params, Map<String, List<String>> filePaths) {
OkHttpClient client = new OkHttpClient();
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
Iterator<String> it = params.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
String value = params.get(key).toString();
try {
value = URLEncoder.encode(value, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
builder.addFormDataPart(key, value);
}
Iterator<String> iterator = filePaths.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
List<String> fileObjects = filePaths.get(key);
if (fileObjects != null) {
for (int i = 0; i < fileObjects.size(); i++) {
String fileObject = fileObjects.get(i);
if (fileObject == null) continue;
String filePath = fileObject;
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
byte[] bytes = getImage(filePath);
System.out.println(fileName + " " + (bytes.length / 1024) + "kb");
builder.addFormDataPart(key, fileName, RequestBody.create(filePath, bytes));
}
}
}
MultipartBody requestBody = builder.build();
Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
Request request = requestBuilder.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("请求失败 " + response);
return response.body().toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
3.下载文件
/**
*
* @param url 下载文件url
* @param saveFile 下载文件地址
*/
public static void downFile(String url, String saveFiler){
OkHttpClient client = new OkHttpClient();
Request request=new Request.Builder().url(url).build();
try {
Response response=client.newCall(request).execute();
if(!response.isSuccessful()){
throw new IOException("网络请求失败"+response);
}
getFile(response.body().byteStream(),saveFile);
} catch (IOException e) {
e.printStackTrace();
}
}
文件写入的位置
/**
* 文件的写入之后的保存
* @param in
* @param saveFile
*/
private static void getFile(InputStream in,String saveFile){
File file = new File(saveFile);
//判断文件是否存在,如果不存在报错
if (!file.exists()) {
SuperLog.e("mkdir " + saveFile + " result " + file.mkdirs());
}
try {
OutputStream out =new FileOutputStream(file);
byte[] buffer = new byte[2048];
int len = 0;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}