OkHttp3 + retrofit2 封装
生活随笔
收集整理的這篇文章主要介紹了
OkHttp3 + retrofit2 封装
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
0.下載文件
1.gradle 添加
compile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.9.0'
?
2.AndroidManifest.xml 權(quán)限
<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
3.Application中初始化?
HttpUtil.getInstance().init(this, "http://baiqi.ej-cloud.com:8070/iot/");4.調(diào)用
HttpUtil.getInstance().get(new HttpUtil.Builder().url("user/token/init").params("key", "1").params("type", "4").callBackSuccess(new CallBackSuccess() {@Overridepublic void onSuccess(String json) {TopicResponse topicResponse = JsonUtil.fromJson(json, TopicResponse.class);tv.setText(topicResponse.data.id);}}));?5.添加上傳圖片功能?HttpUtil.java文件中
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");public void uploadImages(List<String> selectedImages, String url) {// mImgUrls為存放圖片的url集合MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);for (int i = 0; i < selectedImages.size(); i++) {File f = new File(selectedImages.get(i));if (f != null) {builder.addFormDataPart("img" + i, f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));}}MultipartBody requestBody = builder.build();//構(gòu)建請求Request request = new Request.Builder().url(url)//地址.post(requestBody)//添加請求體 .build();okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {@Overridepublic void onFailure(okhttp3.Call call, IOException e) {Log.wtf(TAG, "request " + call.request().url());Log.wtf(TAG, "上傳失敗:e.getLocalizedMessage() = " + e.getLocalizedMessage());}@Overridepublic void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {Log.wtf(TAG, "request " + call.request().url());Log.wtf(TAG, "上傳照片成功:response = " + response.body().string());}});}調(diào)用 ?
HttpUtil.getInstance().uploadImages(selectedImages, "http://baiqi.ej-cloud.com/iotlife/user/opinion/imgUpload&key=1&image=uicon&token="+token+"&feedbackId" +feedbackId );?
參考:
https://github.com/gengqiquan/HttpUtil
https://github.com/hongyangAndroid/okhttputils
轉(zhuǎn)載于:https://www.cnblogs.com/Westfalen/p/6764059.html
總結(jié)
以上是生活随笔為你收集整理的OkHttp3 + retrofit2 封装的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何让springboot中的某些htm
- 下一篇: vue2.0 子组件和父组件之间的传值