首页 > 代码库 > okhttp 常用使用方式 封装 演示
okhttp 常用使用方式 封装 演示
工具介绍
使用:
- AndroidStudio:【compile ‘com.squareup.okhttp3:okhttp:3.4.2‘】和【compile ‘com.zhy:okhttputils:2.6.2‘】和【compile ‘com.google.code.gson:gson:2.3.1‘】
- eclipse:添加okthttp、okio、gson的jar包,复制okhttputils的源码到项目中
封装的功能
- 一般的get请求
- 一般的post请求
- 基于Http Post的文件上传(类似表单)
- 文件下载/加载图片
- 上传下载的进度回调
- 支持取消某个请求
- 支持自定义Callback
- 支持HEAD、DELETE、PATCH、PUT
- 支持session的保持
- 支持自签名网站https的访问,提供方法设置下证书就行
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />android:name="com.bqt.okhttp.MyApplication"
Application
public class MyApplication extends Application {@Overridepublic void onCreate() {super.onCreate();//对于Https,框架中提供了一个类HttpsUtils,可设置为:可访问所有的https网站、设置具体的证书、双向认证//同样的,框架中只是提供了几个实现类,你可以自行实现SSLSocketFactory,传入sslSocketFactory方法中即可HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);//对于cookie,直接通过cookiejar方法配置,当然也可以自己实现CookieJar接口,编写cookie管理相关代码。//对于持久化cookie,还可以使用https://github.com/franmontiel/PersistentCookieJar.相当于框架中只是提供了几个实现类,你可以自行定制或者选择使用// ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));// CookieJarImpl cookieJar = new CookieJarImpl(new MemoryCookieStore());OkHttpClient okHttpClient = new OkHttpClient.Builder()//.connectTimeout(10000L, TimeUnit.MILLISECONDS)//.readTimeout(10000L, TimeUnit.MILLISECONDS)////对于Log,初始化OkhttpClient时,通过设置拦截器实现,框架中提供了一个LoggerInterceptor,当然你可以自行实现一个Interceptor.addInterceptor(new LoggerInterceptor("TAG"))//// .cookieJar(cookieJar).hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}})//.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)//.build();//默认情况下,将直接使用okhttp默认的配置生成OkhttpClient,如果有任何配置,记得在Application中调用initClient方法进行设置。OkHttpUtils.initClient(okHttpClient);}}
MainActivity
public class MainActivity extends ListActivity {private User mUser;private String user = "103468";private String pass = "103468";private String session_id;private String uid;private String mBaseUrl = "http://tapi.95xiu.com/";private TextView mTv;private ImageView mImageView;private ProgressBar mProgressBar;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);String[] array = { "post方式提交键值对数据", "get方式提交键值对数据", "post方式提交键值对数据文件", "post方式提交文件",//"post方式提交Json数据", "get方式获取图片", "get方式下载文件", "清除Session", };for (int i = 0; i < array.length; i++) {array[i] = i + "、" + array[i];}mTv = new TextView(this);// 将内容显示在TextView中mTv.setTextColor(Color.BLUE);mTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);mTv.setPadding(20, 10, 20, 10);mImageView = new ImageView(this);mProgressBar = new ProgressBar(this);mProgressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);mProgressBar.setMax(100);getListView().addFooterView(mProgressBar);getListView().addFooterView(mTv);getListView().addFooterView(mImageView);setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>(Arrays.asList(array))));}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {switch (position) {case 0:postWithParams(); //post方式提交键值对数据break;case 1:getWithParams(); //get方式提交键值对数据break;case 2:postParamsAndFile(); //post方式提交键值对数据,同时提交文件break;case 3:postFile();//post方式提交文件---------------------用不到break;case 4:postJson();//post方式提交Json数据break;case 5:getImage();//get方式获取图片break;case 6:downloadFile();//get方式下载文件break;case 7:clearSession();//清除Sessionbreak;}}//post方式提交键值对数据public void postWithParams() {String url = mBaseUrl + "user/loginv2.php";OkHttpUtils.post().url(url).addParams("user", user).addParams("pass", pass).build().execute(new StringCallback() {@Overridepublic void onBefore(Request request, int id) {mTv.setText("onBefore...\n\n");}@Overridepublic void onAfter(int id) {mTv.append("onAfter...");}@Overridepublic void onError(Call call, Exception e, int id) {e.printStackTrace();mTv.append("onError:" + e.getMessage() + "\n\n");}@Overridepublic void onResponse(String response, int id) {mTv.append(response + "\n\n");Log.i("bqt", response);mUser = new Gson().fromJson(response, User.class);uid = mUser.getMsg().getId();session_id = mUser.getMsg().getSession_id();}});}//get方式提交键值对数据public void getWithParams() {String url = mBaseUrl + "app/news/index.php";OkHttpUtils.get().url(url).id(100).addParams("session_id", session_id).addParams("uid", uid).build().execute(new MyStringCallback());}//post方式提交键值对数据,同时提交文件public void postParamsAndFile() {String url = mBaseUrl + "myprofile/editinfo.php";File file = new File(Environment.getExternalStorageDirectory(), "bqt.jpg");if (!file.exists()) {Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show();return;}Map<String, String> params = new HashMap<>();params.put("session_id", session_id);params.put("uid", uid);OkHttpUtils.post().addFile("image", "文件名", file).url(url).params(params).build().execute(new MyStringCallback());//可以提交多个文件}//post方式提交文件---------------------用不到public void postFile() {String url = "http://app.fulijr.com/api/v1.3.4/a61000b6a80a";File file = new File(Environment.getExternalStorageDirectory(), "bqt.jpg");if (!file.exists()) {Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show();return;}OkHttpUtils.postFile().url(url).file(file).build().execute(new MyStringCallback());}//post方式提交Json数据public void postJson() {String url = mBaseUrl + "user/loginv2.php";OkHttpUtils.postString().url(url).mediaType(MediaType.parse("application/json; charset=utf-8")).content(new Gson().toJson(mUser)).build().execute(new MyStringCallback());}//get方式获取图片public void getImage() {String url = "http://d.hiphotos.baidu.com/image/pic/item/e4dde71190ef76c6cc15d5839816fdfaae516756.jpg";OkHttpUtils.get().url(url).tag(this).build().connTimeOut(20000).readTimeOut(20000).writeTimeOut(20000)//.execute(new BitmapCallback() {@Overridepublic void onError(Call call, Exception e, int id) {mTv.setText("onError:" + e.getMessage());}@Overridepublic void onResponse(Bitmap bitmap, int id) {mImageView.setImageBitmap(bitmap);}});}//get方式下载文件public void downloadFile() {String url = "http://d.hiphotos.baidu.com/image/pic/item/e4dde71190ef76c6cc15d5839816fdfaae516756.jpg";String filePath = Environment.getExternalStorageDirectory().getAbsolutePath();OkHttpUtils.get().url(url).build().execute(new FileCallBack(filePath, "包青天.jpg") {@Overridepublic void onBefore(Request request, int id) {mTv.setText("onBefore...\n\n");}@Overridepublic void onAfter(int id) {mTv.append("onAfter...");}@Overridepublic void inProgress(float progress, long total, int id) {mProgressBar.setProgress((int) (100 * progress));mTv.append(progress + "\n");}@Overridepublic void onError(Call call, Exception e, int id) {e.printStackTrace();mTv.append("onError:" + e.getMessage() + "\n\n");}@Overridepublic void onResponse(File file, int id) {mTv.append(file.getAbsolutePath() + "\n\n");}});}//清除Sessionpublic void clearSession() {CookieJar cookieJar = OkHttpUtils.getInstance().getOkHttpClient().cookieJar();if (cookieJar instanceof CookieJarImpl) {((CookieJarImpl) cookieJar).getCookieStore().removeAll();}}//其他请求方式public void otherRequestDemo() {//also can use delete ,head , patchOkHttpUtils.put().url("http://11111.com").requestBody("may be something").build()//.execute(new MyStringCallback());try {OkHttpUtils.head().url("http://11111.com").addParams("name", "zhy").build().execute();} catch (IOException e) {e.printStackTrace();}}@Overrideprotected void onDestroy() {super.onDestroy();OkHttpUtils.getInstance().cancelTag(this);}public class MyStringCallback extends StringCallback {@Overridepublic void onError(Call call, Exception e, int id) {e.printStackTrace();mTv.setText("onError:" + e.getMessage());}@Overridepublic void onResponse(String response, int id) {mTv.setText("onResponse:" + decodeUnicodeToString(response));}}/**将Unicode编码解析成字符串形式(如汉字) */public static String decodeUnicodeToString(String uString) {StringBuilder sb = new StringBuilder();int i = -1, pos = 0;while ((i = uString.indexOf("\\u", pos)) != -1) {sb.append(uString.substring(pos, i));if (i + 5 < uString.length()) {pos = i + 6;sb.append((char) Integer.parseInt(uString.substring(i + 2, i + 6), 16));}}sb.append(uString.substring(pos));return sb.toString();}}
来自为知笔记(Wiz)
附件列表
okhttp 常用使用方式 封装 演示
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。