java okhttp使用_java 中OkHttp的使用方法及实例详解

这篇文章主要介绍了java 中OkHttp的使用方法及实例的相关资料,需要的朋友可以参考下

java 中OkHttp的使用方法及实例

概述

准备研究Retrofit,而它是依赖OkHttp的,所以先使用一下OkHttp,不深究源码,只探究使用方法。以后有机会再翻查源码。

在进行之前,首先需要2个jar包,其中一个是okHttp的jar包,github上可以下载,另一个是它的依赖包,这个很关键,没有它,项目就无法运行。

OkHttp请求的2种方式

不难猜测,涉及到网络请求,那么无非2种方式,一种是使用回调,另一种则是开启子线程执行。

第一种:开启子线程执行OkHttpClient client = new OkHttpClient();

Request build = new Request.Builder().url(url).build();

try {

Response execute = client.newCall(build).execute();

if(execute.isSuccessful()){

System.out.println("wisely aaa");

} else {

System.out.println("wisely bbb");

}

} catch (IOException e) {

e.printStackTrace();

}

第二种:使用回调,我个人最喜欢使用这种。(PS:觉得自己真是too young too simple!!本来以为回调的方法是在主线程,结果发现,竟然是子线程,子线程....)OkHttpClient client = new OkHttpClient();

Request build = new Request.Builder().url(url).build();

client.newCall(build).enqueue(new Callback() {

@Override

public void onResponse(Response arg0) throws IOException {

System.out.println("wisely success");

}

@Override

public void onFailure(Request arg0, IOException arg1) {

System.out.println("wisely failure");

}

});

OkHttp之get请求

1、获取图片OkHttpClient client = new OkHttpClient();

Request build = new Request.Builder().url(url).build();

client.newCall(build).enqueue(new Callback() {

@Override

public void onResponse(Response response) throws IOException {

// byte[] bytes = response.body().bytes();

InputStream is = response.body().byteStream();

Options options = new BitmapFactory.Options();

options.inSampleSize = 8;

// Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,options);

Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);

Message msg = handler.obtainMessage();

msg.obj = bitmap;

handler.sendMessage(msg);

}

@Override

public void onFailure(Request arg0, IOException arg1) {

System.out.println("wisely fail:"+arg1.getCause().getMessage());

}

});

只写了关键代码,并未写handler的相关代码。

获取网络图片有2种方式,1是获取byte数组,2是获取输入流。注意,onResponse在子线程中...

OkHttp之post请求

比起get请求,post请求的分类略多。

1、首先是最常用的表单提交。OkHttpClient client = new OkHttpClient();

RequestBody body = new FormEncodingBuilder()

.add("userName", "13363114390")

.add("password", "200820e3227815ed1756a6b531e7e0d2").build();

Request build = new Request.Builder().url(url).post(body).build();

client.newCall(build).enqueue(new Callback() {

@Override

public void onResponse(Response response) throws IOException {

String lenght = response.header("Content-Length");

System.out.println("wisely--lenght:" + lenght);

LoginResponse loginResponse = new Gson().fromJson(response.body().charStream(), LoginResponse.class);

System.out.println("wisely---" + loginResponse.getMessage());

}

@Override

public void onFailure(Request arg0, IOException arg1) {

System.out.println("wisely-----fail");

}

});String tokeId;

boolean result;

public boolean isResult() {

return result;

}

public void setResult(boolean result) {

this.result = result;

}

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

public String getTokeId() {

return tokeId;

}

public void setTokeId(String tokeId) {

this.tokeId = tokeId;

}

}

上面的是一个简单的登录表单的提交,其中将返回的json数据封装到了一个bean中。除了能够获取json数据外,还能获取到各个消息头。

2、上传图片

这是我最关心的一个功能,实验证明,okHttp上传图片的功能确实强大,支持多图片上传。private MediaType PNG = MediaType.parse("application/octet-stream");OkHttpClient client = new OkHttpClient();

RequestBody body = new MultipartBuilder()

.type(MultipartBuilder.FORM)

.addPart(Headers.of("Content-Disposition","form-data; name=\"files\";filename=\"img1.jpg\""),RequestBody.create(PNG, file1))

.addPart(Headers.of("Content-Disposition","form-data; name=\"files\";filename=\"img2.jpg\""),RequestBody.create(PNG, file2)).build();

Request request = new Request.Builder()

.url(url)

.post(body).build();

client.newCall(request).enqueue(new Callback() {

@Override

public void onResponse(Response response) throws IOException {

if(response.isSuccessful()){

UploadPNGResponse uploadPNGResponse = new Gson().fromJson(response.body().charStream(), UploadPNGResponse.class);

String msg = uploadPNGResponse.getMsg();

List list = uploadPNGResponse.getList();

for (String string : list) {

System.out.println("wisely---path:"+string);

}

}

}

@Override

public void onFailure(Request arg0, IOException arg1) {

System.out.println("wisely---fail--"+arg1.getCause().getMessage());

}

});class UploadPNGResponse{

String msg;

boolean result;

List list;

public String getMsg() {

return msg;

}

public void setMsg(String msg) {

this.msg = msg;

}

public boolean isResult() {

return result;

}

public void setResult(boolean result) {

this.result = result;

}

public List getList() {

return list;

}

public void setList(List list) {

this.list = list;

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值