OKHTTP的下载和上传
OKHTTP的简介
OKHTTP是一种第三方的网络下载工具,有get和post请求,一般get用来下载,post用来上传。一般是用来封装成工具类来使用的。
OKHTTP的get请求的工具类
public void get(final Map<String,String> hashMap) {
OkHttpClient client = new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS)
.connectTimeout(20,TimeUnit.SECONDS).build();
final Request request = new Request.Builder().get().url(hashMap.get("data")).build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.i(TAG, "onFailure: "+"失败");
}
@Override
public void onResponse(okhttp3.Call call, Response response) throws IOException {
Log.i(TAG, "onResponse: "+"开始下载");
String pase = "/sdcard/Music";
InputStream inputStream = response.body().byteStream();
int len = 0;
byte[] bytes = new byte[19];
FileOutputStream fileOutputStream = new FileOutputStream(new File(pase + "/" + hashMap.get("name")+".mp3"));
while ((len = inputStream.read(bytes)) != -1){
fileOutputStream.write(bytes);
}
Log.i(TAG, "onResponse: "+"下载完成!");
}
});
}
OKHTTP的post请求的工具类
public void post(String urlStr, HashMap<String,String> hashMap){
OkHttpClient client = new OkHttpClient.Builder().build();
FormBody.Builder formBody = new FormBody.Builder();
for (String key:hashMap.keySet()){
formBody.add(key,hashMap.get(key));
}
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("hh",hashMap.get("name")+".mp3",
RequestBody.create(MediaType.parse("media/mp3"),"/sdcard/"+hashMap.get("name")+".mp3"));
MultipartBody body1 = builder.build();
Request request = new Request.Builder().post(body1).url(urlStr).build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.i(TAG, "onFailure: "+"失败");
}
@Override
public void onResponse(okhttp3.Call call, Response response) throws IOException {
String string = response.body().string();
Log.i(TAG, "onResponse: "+"成功"+string);
}
});
}