您的位置:首页 > 理论基础 > 计算机网络

Okhttp的借口调用 和Banner实现学习下okhttp还是蛮必要的,本篇博客首先介绍okhttp的简单使用

2017-10-15 20:44 741 查看




一、概述

最近在群里听到各种讨论okhttp的话题,可见okhttp的口碑相当好了。再加上Google貌似在6.0版本里面删除了HttpClient相关API,对于这个行为不做评价。为了更好的在应对网络访问,学习下okhttp还是蛮必要的,本篇博客首先介绍okhttp的简单使用,主要包含:一般的get请求
一般的post请求
基于Http的文件上传
文件下载
加载图片
支持请求回调,直接返回对象、对象集合
支持session的保持
最后会对上述几个功能进行封装,完整的封装类的地址见:https://github.com/hongyangAndroid/okhttp-utils使用前,对于Android Studio的用户,可以选择添加:
compile 'com.squareup.okhttp:okhttp:2.4.0'
1
或者Eclipse的用户,可以下载最新的jar okhttp he latest JAR ,添加依赖就可以用了。注意:okhttp内部依赖okio,别忘了同时导入okio:gradle: 
compile 'com.squareup.okio:okio:1.5.0'
最新的jar地址:okio the latest JAR

二、使用教程

(一)Http Get

对了网络加载库,那么最常见的肯定就是http get请求了,比如获取一个网页的内容。
//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
//创建一个Request
final Request request = new Request.Builder()
.url("https://github.com/hongyangAndroid")
.build();
//new call
Call call = mOkHttpClient.newCall(request);
//请求加入调度
call.enqueue(new Callback()
{
@Override
public void onFailure(Request request, IOException e)
{
}

@Override
public void onResponse(final Response response) throws IOException
{
//String htmlStr =  response.body().string();
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
以上就是发送一个get请求的步骤,首先构造一个Request对象,参数最起码有个url,当然你可以通过Request.Builder设置更多的参数比如:
header
method
等。
然后通过request的对象去构造得到一个Call对象,类似于将你的请求封装成了任务,既然是任务,就会有
execute()
cancel()
等方法。
最后,我们希望以异步的方式去执行请求,所以我们调用的是call.enqueue,将call加入调度队列,然后等待任务执行完成,我们在Callback中即可得到结果。
看到这,你会发现,整体的写法还是比较长的,所以封装肯定是要做的,不然每个请求这么写,得累死。ok,需要注意几点:
=========================

xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.eightgroup.zk2lianxi.Main3Activity">
<com.youth.banner.Banner
android:id="@+id/mybanner"
android:layout_below="@+id/ss"
android:layout_width="match_parent"
android:layout_height="150dp">

</com.youth.banner.Banner>

<android.support.v7.widget.RecyclerView
android:layout_below="@+id/mybanner"
android:id="@+id/id_recyclerview"
android:divider="#ffff0000"
android:dividerHeight="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="@+id/ss"

android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:layout_marginLeft="50dp"
android:layout_width="300dp"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
android:hint="收搜关键字"
/>
<Button
android:id="@+id/b5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="切换"
/>

</LinearLayout>
</RelativeLayout>

<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="120dp"
android:id="@+id/swipeRefreshLayout"
>
<android.support.v7.widget.RecyclerView
android:layout_below="@+id/mybanner"
android:id="@+id/id_recyclerview"
android:divider="#ffff0000"
android:dividerHeight="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>

SwipeRefreshLayout swipeRefreshLayout;
swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipeRefreshLayout);
implements SwipeRefreshLayout.OnRefreshListener
//uri
swipeRefreshLayout.setOnRefreshListener(this);
//请求成功
//判断什么加载成功后刷新停止
if (swipeRefreshLayout.isRefreshing()){
swipeRefreshLayout.setRefreshing(false);
}
//内部类的上面
//刷新监听
@Override
public void onRefresh() {
getData(urii);
}




ViewPager逻辑处理1. 填充数据(自定义Adapter)2. 设置页面切换监听事件3. 在自定义adapter中的instantiateItem方法设置ViewPager点击事件
这里我们的图片是从网上下载的,用到了universal-image-loader-1.8.6-with-sources.jar这个类库,可以实现异步加载图片,具体使用查看代码。

最后给出完整代码:/BannerAutoScrollDemo/src/com/xiaowu/banner/demo/MainActivity.java


、、 ===========对应的依赖注入

ompile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
//三个版本
compile 'com.android.support:mediarouter-v7:24.0.0'
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.android.support:recyclerview-v7:24.0.0'
//Okhttp三个依赖注入
compile 'com.squareup.okio:okio:1.5.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
json.jar包
compile 'com.google.code.gson:gson:2.8.2'
//图片
compile files('libs/universal-image-loader-1.9.3.jar')
//实现轮廓图的依赖
compile 'com.youth.banner:banner:1.4.9'
compile 'com.github.bumptech.glide:glide:3.7.0'

//
相关权限
//网络权限读写,判断网络 Bannner轮廓图
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
android:name=".app.MyApp" //图片加载




一、概述

最近在群里听到各种讨论okhttp的话题,可见okhttp的口碑相当好了。再加上Google貌似在6.0版本里面删除了HttpClient相关API,对于这个行为不做评价。为了更好的在应对网络访问,学习下okhttp还是蛮必要的,本篇博客首先介绍okhttp的简单使用,主要包含:一般的get请求
一般的post请求
基于Http的文件上传
文件下载
加载图片
支持请求回调,直接返回对象、对象集合
支持session的保持
最后会对上述几个功能进行封装,完整的封装类的地址见:https://github.com/hongyangAndroid/okhttp-utils使用前,对于Android Studio的用户,可以选择添加:
compile 'com.squareup.okhttp:okhttp:2.4.0'
1
或者Eclipse的用户,可以下载最新的jar okhttp he latest JAR ,添加依赖就可以用了。注意:okhttp内部依赖okio,别忘了同时导入okio:gradle: 
compile 'com.squareup.okio:okio:1.5.0'
最新的jar地址:okio the latest JAR//Banner的必有接口public class GlideImaGlideImageLoader extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context).load(path).into(imageView);
}

}

、、下面就是主函数
public class Main3Activity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private HomeAdapter mAdapter;
List<News.NewslistBean> mDatas;
ImageLoader imagerloder;
Banner mbanner;
Button b5;
int i;

@Override
protected void onCreate(Bundle savedInstanceState)
c8cb
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
img = (ImageView) findViewById(R.id.img);
tv = (TextView) findViewById(R.id.tv);
b5=(Button)findViewById(R.id.b5);
mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);
b5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (i % 2 == 0) { mRecyclerView.setLayoutManager(new LinearLayoutManager(Main3Activity.this)); i++; }else{ mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); i++; } } });
//listview的效果
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//下划线
/*mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
DividerItemDecoration.VERTICAL_LIST));*/
//groupview的效果
/* mRecyclerView.setLayoutManager(new GridLayoutManager(this,3));*/
//瀑布效果
/* mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(5, StaggeredGridLayoutManager.VERTICAL));*/

//网络判断
boolean netWorkAvailable = NetWorkUtils.isNetWorkAvailable(this);
if (!netWorkAvailable) {
Toast.makeText(Main3Activity.this, "联网:" + netWorkAvailable, Toast.LENGTH_SHORT).show();
}

mbanner= (Banner) findViewById(R.id.mybanner);
getData(uri);

}
public void getData( String uri) {
OkHttp3Utils.getInstance().doGet(uri, new GsonObjectCallback<News>() {
@Override
public void onUi(News news) {
List<String> mlist = new ArrayList<String>();
for(int i=0; i<news.getNewslist().size();i++){
String ad1s = news.getNewslist().get(i).getPicUrl();
mlist.add(ad1s);
}
//设置图片加载器
mbanner.setImageLoader(new GlideImageLoader());
mbanner.setImages(mlist);
mbanner.start();

mDatas = new ArrayList<News.NewslistBean>();
Log.d("mylog",news.getNewslist().get(0).getTitle()+"成功");
mDatas = news.getNewslist();
mRecyclerView.setAdapter(mAdapter = new HomeAdapter());

}

@Override
public void onFailed(Call call, IOException e) {

}
});

}

class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
Main3Activity.this).inflate(R.layout.item, parent,
false));
return holder;
}
public void onBindViewHolder(final MyViewHolder holder, final int position) {

holder.tv.setText(mDatas.get(position).getTitle());
imagerloder = ImageLoader.getInstance();
imagerloder.displayImage(mDatas.get(position).getPicUrl(), holder.img);
// 获得该控件的所有属性
ViewGroup.LayoutParams layoutParams = holder.tv.getLayoutParams();
Random random = new Random();
layoutParams.height = random.nextInt(200) + 50;
holder.tv.setLayoutParams(layoutParams);
}

@Override
public int getItemCount()
{
return mDatas.size();
}

class MyViewHolder extends RecyclerView.ViewHolder
{

TextView id_num;
ImageView img;
TextView tv;
public MyViewHolder(View view)
{
super(view);
tv = (TextView)view.findViewById(R.id.tv);

img = (ImageView)view.findViewById(R.id.img);
}
}

}

}

二、使用教程

(一)Http Get

对了网络加载库,那么最常见的肯定就是http get请求了,比如获取一个网页的内容。

源码地址okhttp-utils,大家可以自己下载查看。欢迎关注我的微博: 
http://weibo.com/u/3165018720群号:463081660,欢迎入群微信公众号:hongyangAndroid 
(欢迎关注,第一时间推送博文信息) 


参考文章

https://github.com/square/okhttp
http://square.github.io/okhttp/
泡网OkHttp使用教程
顶232 踩18  上一篇Volley 图片加载相关源码解析
下一篇Android Https相关完全解析 当OkHttp遇到Https
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: