一.準(zhǔn)備工作
在dependencies中添加依賴
compile'com.squareup.okhttp3:okhttp:3.2.0'
在配置文件AndroidManifest.xml中添加網(wǎng)絡(luò)訪問(wèn)權(quán)限以及讀取本地文件的權(quán)限
<uses-permission android:name="android.permission.INTERNET" /><!-- 網(wǎng)絡(luò)訪問(wèn)權(quán)限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <!-- sdcard讀權(quán)限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!-- sdcard寫權(quán)限 -->
二.完成okhttp3請(qǐng)求的代碼封裝
首先我們分析一般請(qǐng)求的可能性
- 1.無(wú)參數(shù)的get請(qǐng)求
- 2.有參數(shù)的post請(qǐng)求
- 3.上傳文件的post請(qǐng)求
- 4.下載文件的請(qǐng)求
大概步驟
- 1.建立一個(gè)OkhttpClient 連接 eg:OkHttpClient client=new OkHttpClient();//建立一個(gè)連接
- 2.要是需要進(jìn)行request的body 就需要進(jìn)行 對(duì)實(shí)體的添加請(qǐng)求的參數(shù)。eg:RequestBody rbody=RequestBody.create(CONTENT_TYPE,getParams(params).getBytes());
- 3.建立請(qǐng)求實(shí)體 request eg: Request request =new Request.Builder().url(url).build();
- 4..響應(yīng)的接收Response 的操作 eg:Response response = client.newCall(request).execute()
- 5.返回結(jié)果body eg:body.string()焙格;
- 6.還有一些其他的比如Builder類 Header類等等角虫。
1.無(wú)參get請(qǐng)求/和有參數(shù)的post
/**
* @param url 請(qǐng)求地址
* @param params 參數(shù)(有參數(shù)輸入?yún)?shù))(無(wú)參數(shù)輸入null)
* @return
*/
public static String postHtml(String url, Map<String, Object> params) {
//鏈接的建立
OkHttpClient client = new OkHttpClient();
//請(qǐng)求的設(shè)置
Request.Builder builder = new Request.Builder().url(url);
//請(qǐng)求體的制作
if (!params.isEmpty() && params != null) {
RequestBody requestBody = RequestBody.create(CONTENT_TYPE, parseParams(params).getBytes());
builder.post(requestBody);
}
Request request = builder.build();
//響應(yīng)的接收
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("請(qǐng)求失敗 " + response);
}
ResponseBody responseBody = response.body();
return responseBody.string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
請(qǐng)求的入?yún)⒌暮喜⒊蒪yte格式
/**
* 參數(shù)的合并
*
* @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 請(qǐng)求地址
* @param params 參數(shù)(有參數(shù)輸入?yún)?shù))(無(wú)參數(shù)輸入null)
* @param filePaths 圖片地址(有參數(shù)輸入?yún)?shù))
* @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("請(qǐng)求失敗 " + 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("網(wǎng)絡(luò)請(qǐng)求失敗"+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);
//判斷文件是否存在壕吹,如果不存在報(bào)錯(cuò)
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();
}
}