OkHttp分为get post
get主要获取数据
post主要用户上传数据文件
private void get() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
Request request = new Request.Builder().url(“http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&itemid=2&act=ad_app”).get().build();
Call call = builder.build().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, “onFailure: 请求失败:”+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
Log.i(TAG, "onResponse: "+string);
}
});
}
private void post() {
//act=column&ctype=2&mid=16
FormBody formBody = new FormBody.Builder().
add(“act”,“column”).
add(“ctype”,“2”).
add(“mid”,“16”).
build();
final Request request = new Request.Builder().
url(“http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&”).
post(formBody).
build();
new OkHttpClient.Builder().build().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "onResponse:\\ Post:"+response.body().string());
}
});
}
private void downLoad() {
Request request = new Request.Builder().url("http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4").get().build();
new OkHttpClient.Builder().build().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = response.body().byteStream();
long l = response.body().contentLength();
max=(int)l;
byte[] bytes = new byte[1024];
int len=0;
FileOutputStream fos = new FileOutputStream("/sdcard/Movies/aa.mp4");
while ((len=is.read(bytes)) != -1){
count+=len;
fos.write(bytes,0,len);
Log.i(TAG, "onResponse: "+count);
Message message = new Message();
message.what=110;
message.arg1=count;
handler.sendMessage(message);
}
}
});
}
private void upF() {
OkHttpClient client = new OkHttpClient.Builder()
.build();
//上传文件的请求体
MultipartBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(“file”, “xyb.mp4”,//aaaa.mp3 服务器端的名字
RequestBody.create(MediaType.parse(“media/mp4”), new File("/sdcard/Movies/aa.mp4")))
.build();
final Request request = new Request.Builder()
.url(“http://169.254.113.244/hfs/”)
.post(requestBody)//post提交必须要设置请求体 http://169.254.113.244/hfs/
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}