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 权限
<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.调用
HttpUtil.getInstance().get(
new HttpUtil.Builder()
.url("user/token/init")
.params("key", "1")
.params("type", "4")
.callBackSuccess(new CallBackSuccess() {
@Override
public 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();
//构建请求
Request request = new Request.Builder()
.url(url)//地址
.post(requestBody)//添加请求体
.build();
okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.wtf(TAG, "request " + call.request().url());
Log.wtf(TAG, "上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
} @Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
Log.wtf(TAG, "request " + call.request().url());
Log.wtf(TAG, "上传照片成功:response = " + response.body().string());
}
});
}
调用
HttpUtil.getInstance().uploadImages(selectedImages, "http://baiqi.ej-cloud.com/iotlife/user/opinion/imgUpload&key=1&image=uicon&token="
+token+"&feedbackId" +feedbackId );
参考: