Okhttp网络请求
来源:互联网 发布:pdf阅读器有没有mac 编辑:程序博客网 时间:2024/06/05 06:34
adapter包
MyAdapter
package adapter;import android.content.Context;import android.content.Intent;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;import com.bwie.okhttpdemotext.Main2Activity;import com.bwie.okhttpdemotext.R;import com.nostra13.universalimageloader.core.ImageLoader;import java.util.List;import bean.Bean;/** * Created by 王爱诗 on 2017/10/25. */public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; private List<Bean.DataBean> list; private OnItemListener onItemListener; public MyAdapter(Context context,List<Bean.DataBean> list){ this.context=context; this.list=list; } public interface OnItemListener{ public void onItemClick(Bean.DataBean dataBean); } public void setonItemListener(OnItemListener onItemListener){ this.onItemListener=onItemListener; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item,null); return new MyApter(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { MyApter holder1=(MyApter)holder; holder1.tv.setText(list.get(position).getOccupation()); holder1.tv1.setText(list.get(position).getIntroduction()); ImageLoader.getInstance().displayImage(list.get(position).getUserImg(),holder1.iv_urlimage); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(context, Main2Activity.class); intent.putExtra("title",list.get(position).getTitle()); intent.putExtra("url",list.get(position).getUrl()); context.startActivity(intent); } }); } @Override public int getItemCount() { return list.size(); } class MyApter extends RecyclerView.ViewHolder{ private TextView tv,tv1; private final ImageView iv_urlimage; public MyApter(View itemView) { super(itemView); tv= itemView.findViewById(R.id.tv); tv1= itemView.findViewById(R.id.tv1); iv_urlimage = itemView.findViewById(R.id.iv_urlimage); } }}bean包BaseBean
package bean; public class BaseBean { public int code; public int getCode() { return code; } public void setCode(int code) { this.code = code; }}
Beanpackage bean;import java.util.List;/** * Created by 王爱诗 on 2017/10/25. */public class Bean extends BaseBean{ // private int code; private boolean success; private int width; private int height; private Object message; private List<DataBean> data;// public int getCode() {// return code;// }//// public void setCode(int code) {// this.code = code;// } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public Object getMessage() { return message; } public void setMessage(Object message) { this.message = message; } public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class DataBean { private String userImg; private int impressEditId; private int impressType; private String occupation; private String url; private long createTime; private String hxKey; private String img; private String yulin; private String introduction; private int replyTimes; private String remark; private int click; private long topTime; private int recommend; private int userAge; private int star; private String title; private int source; private String userName; private int reporter; private int status; private String content; public String getUserImg() { return userImg; } public void setUserImg(String userImg) { this.userImg = userImg; } public int getImpressEditId() { return impressEditId; } public void setImpressEditId(int impressEditId) { this.impressEditId = impressEditId; } public int getImpressType() { return impressType; } public void setImpressType(int impressType) { this.impressType = impressType; } public String getOccupation() { return occupation; } public void setOccupation(String occupation) { this.occupation = occupation; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public String getHxKey() { return hxKey; } public void setHxKey(String hxKey) { this.hxKey = hxKey; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getYulin() { return yulin; } public void setYulin(String yulin) { this.yulin = yulin; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public int getReplyTimes() { return replyTimes; } public void setReplyTimes(int replyTimes) { this.replyTimes = replyTimes; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public int getClick() { return click; } public void setClick(int click) { this.click = click; } public long getTopTime() { return topTime; } public void setTopTime(long topTime) { this.topTime = topTime; } public int getRecommend() { return recommend; } public void setRecommend(int recommend) { this.recommend = recommend; } public int getUserAge() { return userAge; } public void setUserAge(int userAge) { this.userAge = userAge; } public int getStar() { return star; } public void setStar(int star) { this.star = star; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getSource() { return source; } public void setSource(int source) { this.source = source; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getReporter() { return reporter; } public void setReporter(int reporter) { this.reporter = reporter; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }}
Main包
Main2Activitypackage com.bwie.okhttpdemotext;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.webkit.WebChromeClient;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.Toast;public class Main2Activity extends AppCompatActivity { private WebView wv; private String url; private String title; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); initView(); initDate(); } private void initDate() { Intent intent = getIntent(); title = intent.getStringExtra("title"); url = intent.getStringExtra("url"); setTitle(title); Toast.makeText(Main2Activity.this,"Url的值是+++++++++++++++++"+ url,Toast.LENGTH_SHORT).show(); wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); wv.getSettings().setJavaScriptEnabled(true); wv.getSettings().setSupportZoom(false); wv.getSettings().setBlockNetworkLoads(true); wv.getSettings().setBlockNetworkImage(true); wv.setWebChromeClient(new WebChromeClient()); wv.setWebViewClient(new WebViewClient()); /* if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP) { wv.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); }*/ runOnUiThread(new Runnable() { @Override public void run() { wv.loadUrl(url); } }); } private void initView() { wv = (WebView) findViewById(R.id.wv); }}BaseActivity
package com.bwie.okhttpdemotext;import android.app.Activity;import android.app.ProgressDialog;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v7.app.AppCompatActivity;import net.HttpUtil;import java.util.LinkedList;/** * Created by peng on 2017/9/27. */public class BaseActivity extends AppCompatActivity { private LinkedList<Activity> list = new LinkedList<>(); protected HttpUtil httpUtil; private ProgressDialog dialog; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); list.add(this); httpUtil = HttpUtil.getInstance(this); } public void finshAll() { for (Activity ac : list) { if (!ac.isFinishing()) { ac.finish(); } } } /** * 显示进度条 */ protected void showPd() { dialog = new ProgressDialog(this); dialog.setMessage("正在加載..."); dialog.show(); } /** * 关闭进度条 */ protected void dismissPd(){ if (dialog!=null && !this.isFinishing()){ dialog.dismiss(); } }}
MainActivity
package com.bwie.okhttpdemotext;import android.os.Bundle;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import com.nostra13.universalimageloader.core.DisplayImageOptions;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;import net.OnNetListener;import java.io.IOException;import adapter.MyAdapter;import bean.BaseBean;import bean.Bean;public class MainActivity extends BaseActivity { private String url="http://www.yulin520.com/a2a/impressApi/news/mergeList?sign=C7548DE604BCB8A17592EFB9006F9265&pageSize=20&gender=2&ts=1871746850&page=1"; private RecyclerView recyc; private MyAdapter adpter; //private List<Bean.DataBean> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyc=(RecyclerView)findViewById(R.id.recyc); httpUtil.doGet(url, Bean.class, new OnNetListener() { @Override public void onSuccess(BaseBean baseBean) throws IOException { Bean bean= (Bean) baseBean; //list=bean.getData(); adpter = new MyAdapter(MainActivity.this,bean.getData()); LinearLayoutManager linearLayoutManager=new LinearLayoutManager(MainActivity.this); recyc.setLayoutManager(linearLayoutManager); recyc.setAdapter(adpter); } @Override public void onError(IOException e) { } }); DisplayImageOptions options=new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisk(true) .build(); ImageLoaderConfiguration config=new ImageLoaderConfiguration.Builder(this) .defaultDisplayImageOptions(options) .build(); ImageLoader.getInstance().init(config); /* httpUtil.doPost(url, null, Bean.class, new OnNetListener() { @Override public void onSuccess(BaseBean baseBean) throws IOException { Bean bean= (Bean) baseBean; MyAdpter adpter = new MyAdpter(MainActivity.this,bean.getData()); LinearLayoutManager linearLayoutManager=new LinearLayoutManager(MainActivity.this); recyc.setLayoutManager(linearLayoutManager); recyc.setAdapter(adpter); } @Override public void onError(IOException e) { } });*/ }}net包BaseNetListener
package net;import java.io.IOException;import bean.BaseBean;public class BaseNetListener implements OnNetListener { @Override public void onSuccess(BaseBean baseBean) throws IOException { } @Override public void onError(IOException e) { }}
HttpUtilpackage net;import android.content.Context;import android.os.Environment;import android.os.Handler;import android.os.Looper;import android.widget.Toast;import com.google.gson.Gson;import java.io.File;import java.io.IOException;import java.util.HashMap;import java.util.Map;import bean.BaseBean;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;import okhttp3.logging.HttpLoggingInterceptor;;/** * Created by peng on 2017/9/27. */public class HttpUtil { private static HttpUtil httpUtil; private final OkHttpClient client; private Context context; private Handler handler = new Handler(Looper.getMainLooper()); private HttpUtil(Context context) { //缓存目录 File sdcache = new File(Environment.getExternalStorageDirectory(), "cache"); int cacheSize = 10 * 1024 * 1024; HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); client = new OkHttpClient.Builder() .addInterceptor(logging)// .addNetworkInterceptor(new CacheInterceptor())// .writeTimeout(20, TimeUnit.SECONDS)// .readTimeout(20, TimeUnit.SECONDS)// .cache(new Cache(sdcache,cacheSize)) .build(); this.context = context; } public static HttpUtil getInstance(Context context) { if (httpUtil == null) { synchronized (HttpUtil.class) { if (httpUtil == null) { httpUtil = new HttpUtil(context); } } } return httpUtil; } public void doPost(String url, Map<String, String> params, final Class clazz, final OnNetListener onNetListener) { //网络判断 if (!NetWorkUtil.isNetworkAvailable(context)) { Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show(); return; } if (params != null && params.size() > 0) { FormBody.Builder builder = new FormBody.Builder(); params.put("client", "android"); for (Map.Entry<String, String> entry : params.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } FormBody formBody = builder.build(); final Request request = new Request.Builder().url(url).post(formBody).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { final BaseBean baseBean = (BaseBean) new Gson().fromJson(response.body().string(), clazz); int code = baseBean.getCode(); handler.post(new Runnable() { @Override public void run() { try { onNetListener.onSuccess(baseBean); } catch (IOException e) { e.printStackTrace(); } } }); } }); } } public void download(String url, Callback callback) { Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(callback); } public void doGet(String url, final Class clazz, final OnNetListener onNetListener) { //网络判断 if (!NetWorkUtil.isNetworkAvailable(context)) { Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show(); return; } Request.Builder builder = new Request.Builder(); builder.url(url); final Request request = builder.build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { onNetListener.onError(e); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); // final BaseBean baseBean = (BaseBean) new Gson().fromJson(string, clazz); final BaseBean baseBean = (BaseBean) new Gson().fromJson(string, clazz); int code = baseBean.getCode(); if (code == 1) { handler.post(new Runnable() { @Override public void run() { try { onNetListener.onSuccess(baseBean); } catch (IOException e) { e.printStackTrace(); } } }); } else if (code == 400) { } else if (code == 300) { } } }); } /** * @param url * @param params * @param header * @param clazz * @param onNetListener */ public void doGet(String url, HashMap<String, String> params, HashMap<String, String> header, final Class clazz, final OnNetListener onNetListener) { //网络判断 if (!NetWorkUtil.isNetworkAvailable(context)) { Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show(); return; } Request.Builder builder = new Request.Builder(); if (params != null && params.size() > 0) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(url); sb.append("?"); sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); } url = sb.toString(); } builder.url(url); //添加请求头 if (params != null && header.size() > 0) { for (Map.Entry<String, String> entry : params.entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } } final Request request = builder.build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { onNetListener.onError(e); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); final BaseBean baseBean = (BaseBean) new Gson().fromJson(string, clazz); int code = baseBean.getCode(); if (code == 200) { handler.post(new Runnable() { @Override public void run() { try { onNetListener.onSuccess(baseBean); } catch (IOException e) { e.printStackTrace(); } } }); } else if (code == 400) { } else if (code == 300) { } } }); } /** * 上传 * * @param url * @param fileName */ public void uploadFile(String url, String fileName) { String file = Environment.getExternalStorageState() + "/" + fileName; RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); //创建RequestBody 设置类型等 RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", fileName, fileBody).build(); Request request = new Request.Builder().url(url).post(requestBody).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); } /** * 下载 * * @param url */ public void download(String url) { Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); }}NetWorkUtil
package net;import android.content.Context;import android.net.ConnectivityManager;import android.net.NetworkInfo;/** * Created by peng on 2017/9/27. */public class NetWorkUtil { // check all network connect, WIFI or mobile public static boolean isNetworkAvailable(final Context context){ boolean hasWifoCon = false; boolean hasMobileCon = false; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo[] networkInfo = cm.getAllNetworkInfo(); for (NetworkInfo net:networkInfo){ String typeName = net.getTypeName(); if(typeName.equalsIgnoreCase("WIFI")){ if(net.isConnected()){ hasWifoCon=true; } } if(typeName.equalsIgnoreCase("MOBILE")){ if(net.isConnected()){ hasWifoCon=true; } } } return hasWifoCon || hasMobileCon; }}
OkhttpUtilspackage net;import android.os.Environment;import android.os.Handler;import android.os.Looper;import java.io.IOException;import java.util.Map;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;import okhttp3.logging.HttpLoggingInterceptor;/** * Created by peng on 2017/10/11. * 使用懒汉式创建该对象,并保证线程安全 */public class OkHttpUtils implements IHttpListener { private static OkHttpUtils okHttpUtils; private final OkHttpClient httpClient; private final Handler handler; //构造方法私有化 private OkHttpUtils() { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BASIC); httpClient = new OkHttpClient.Builder() .addInterceptor(logging) .build(); handler = new Handler(Looper.getMainLooper()); } public static OkHttpUtils getInstance() { if (okHttpUtils == null) { synchronized (OkHttpUtils.class) { if (okHttpUtils == null) { okHttpUtils = new OkHttpUtils(); } } } return okHttpUtils; } /** * post请求 * * @param url * @param params * @param clazz * @param onNetListener */ public void doPost(String url, Map<String, String> params, Class clazz, OnNetListener onNetListener) { FormBody.Builder builder = new FormBody.Builder(); for (Map.Entry<String, String> entry : params.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } FormBody formBody = builder.build(); Request request = new Request.Builder().url(url).post(formBody).build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); } public void doGet(String url, Class clazz, OnNetListener onNetListener) { Request request = new Request.Builder() .url(url) .build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, final Response response) throws IOException { handler.post(new Runnable() { @Override public void run() {// onNetListener.onSuccess(); } }); } }); } public void uploadFile(String url, String fileName) { String file = Environment.getExternalStorageState() + "/" + fileName; RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); //创建RequestBody 设置类型等 RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", fileName, fileBody).build(); Request request = new Request.Builder().url(url).post(requestBody).build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); } public void download(String url) { Request request = new Request.Builder().url(url).build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); }}
OnNetListenerpackage net;import java.io.IOException;import bean.BaseBean;/** * Created by peng on 2017/9/27. */public interface OnNetListener { public void onSuccess(BaseBean baseBean) throws IOException; public void onError(IOException e);}
布局main<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.bwie.okhttpdemotext.MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recyc" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v7.widget.RecyclerView></android.support.constraint.ConstraintLayout>布局main2<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.bwie.okhttpdemotext.Main2Activity"> <WebView android:id="@+id/wv" android:layout_width="match_parent" android:layout_height="match_parent"></WebView></LinearLayout>
布局item1<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/iv_urlimage" android:layout_width="match_parent" android:layout_height="250dp" android:scaleType="centerCrop" /> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv1" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>权限<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
依赖compile 'com.squareup.okhttp3:okhttp:3.9.0'compile 'com.google.code.gson:gson:2.8.2'compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
阅读全文
0 0
- java okhttp 网络请求
- OkHttp网络请求
- OKHttp请求网络数据
- okhttp网络请求框架
- 网络请求框架OKHttp
- OkHttp网络请求
- OkHttp网络请求框架
- OKHttp网络请求
- OkHttp 网络请求
- 网络请求okhttp框架
- OkHttp网络请求
- okHttp网络请求
- oKHttp网络请求
- OkHttp网络请求
- okHttp发起网络请求
- OkHttp网络数据请求
- OkHttp 网络请求
- okhttp网络请求简介
- 各大浏览器清除缓存的快捷键
- Swift协议合成
- angular实现商品加减
- PullToRefresh
- 创建抽象类AA
- Okhttp网络请求
- GeekBand笔记-《STL与泛型编程 》 第四周
- Unity_与线程的关联
- non-local Means(非局部均值)降噪算法及快速算法原理与实现
- Swift协议合成
- Okhttp工具类
- Java:计算圆形和长方形的面积
- 线程的五大状态
- 10月25日 c语言 找到10000以内所有完数