风轻云淡

-------生活没有抱怨,只有自己的不努力,当才华撑不起梦想与野心,不断学习是你唯一的选择。没有伞的孩子必须努力奔跑...

导航

Android Studio开发---Get Post Put Delete 封装okhttp3类

package com.example.xxxxxx.com;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AjaxUtil {
private static AjaxUtil instance;
public String TAG = "mytag";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
public void Post(final String reqUrl, Map<String, String> params, Map<String,File> files, final AnsyCallback ansyCallback){
PostForm(reqUrl,params,files,ansyCallback,0);
}
public void Put(final String reqUrl, Map<String, String> params, Map<String,File> files, final AnsyCallback ansyCallback){
PostForm(reqUrl,params,files,ansyCallback,1);
}
private void PostForm(final String reqUrl, Map<String, String> params, Map<String,File> files, final AnsyCallback ansyCallback,int type) {
Log.v(TAG,"PostForm请求地址:"+reqUrl);
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
ansyCallback.AnsyLoader((String) msg.obj, reqUrl);
}
};
MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
multipartBodyBuilder.setType(MultipartBody.FORM);
//map中所有参数builder
if (params != null) {
for (String key : params.keySet()) {
multipartBodyBuilder.addFormDataPart(key, params.get(key));
}
}
if (files != null) {
for (String file : files.keySet()) {
Log.v(TAG,"file:"+file+"||||file.getName():---"+ files.get(file).getName());
multipartBodyBuilder.addFormDataPart(file, files.get(file).getName(),RequestBody.create(MEDIA_TYPE_PNG, files.get(file)));
}
}
//求体
RequestBody requestBody = multipartBodyBuilder.build();
Request.Builder RequestBuilder = new Request.Builder();
RequestBuilder.url(reqUrl);// 添加URL地址
if(type==1) {
RequestBuilder.put(requestBody);
}else {
RequestBuilder.post(requestBody);
}
Request request = RequestBuilder.build();
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "连接失败" + e.getLocalizedMessage());
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Message message = handler.obtainMessage(0, result);
handler.sendMessage(message);
Log.d(TAG, result);
if (response.body() != null) {
response.body().close();
}
call.cancel();
}
});
}
public static AjaxUtil getInstance() {
if (instance == null) {
instance = new AjaxUtil();
}
return instance;
}
public void Get(final String path, final AnsyCallback ansyCallback)
{
GetData(path,ansyCallback,0);
}
public void Delete(final String path, final AnsyCallback ansyCallback)
{
GetData(path,ansyCallback,1);
}
private void GetData(final String path, final AnsyCallback ansyCallback,int type) {
Log.v(TAG,"Get请求地址:"+path);
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
ansyCallback.AnsyLoader((String) msg.obj, path);
}
};
OkHttpClient client = new OkHttpClient();
Request.Builder RequestBuilder = new Request.Builder();
RequestBuilder.url(path);
if(type==1)
{//delete
RequestBuilder.delete();
}else{
RequestBuilder.get();
}
Request request = RequestBuilder.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "连接失败" + e.getLocalizedMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Message message = handler.obtainMessage(0, result);
handler.sendMessage(message);
Log.d(TAG, result);
if (response.body() != null) {
response.body().close();
}
}
});
}
public void GetImage(final String imgurl,final AnsyImageCallback ansyImageCallback)
{
Log.v(TAG,"GetImage请求地址:"+imgurl);
if(imgurl==null||imgurl=="")
{
return ;
}
final Handler handler=new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
ansyImageCallback.AnsyImageLoader((Bitmap) msg.obj,imgurl);
}
};
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(imgurl)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
public void onFailure(Call call, IOException e) {
Log.d(TAG, "连接图片失败" + e.getLocalizedMessage());
}
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();//得到片的流
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message msg = new Message();
msg.obj = bitmap;
handler.sendMessage(msg);
}
});
}
public interface AnsyCallback {
public void AnsyLoader(String result, String Url);
}
public interface AnsyImageCallback{
public void AnsyImageLoader(Bitmap bitmap, String Url);
}

}

-----------------------------------------------------------------------------------------
调用get:
AjaxUtil.getInstance().Get("请求url 地址", new AjaxUtil.AnsyCallback() {
@Override
public void AnsyLoader(String txt,String Url) {
try {
Log.v(TAG,"内容输出:"+txt);
}catch (Exception ex)
{
Log.v(TAG,ex.getMessage(),ex);
}
}
});
调用Post:
Map<String, String> map = new HashMap<String, String>(); 
map.put("name", txtname.getText().toString());
map.put("remark", editRemark.getText().toString());
Map<String, File> files = new HashMap<String, File>();
File file = new File(FileUtils.getPath(ProductEditActivity.this, "图片Uri:【拍照或选择图片】"));//FileUtils类在下面...
files.put(file.getName(), file);
AjaxUtil.getInstance().Post("Post url 地址", map, files, new AjaxUtil.AnsyCallback() {
@Override
public void AnsyLoader(String result, String Url) {
Log.v(TAG, "Post发送成功!!!!结果:" + result);
}
});


调用put:
AjaxUtil.getInstance().Put("Put url 地址", map, files, new AjaxUtil.AnsyCallback() {
@Override
public void AnsyLoader(String result, String Url) {
Log.v(TAG, "Put发送成功!!!!结果:" + result);
}
});

调用delete:
AjaxUtil.getInstance().Delete("Delete url 地址", new AjaxUtil.AnsyCallback() {
@Override
public void AnsyLoader(String result, String Url) {
Log.v(TAG,"Delete发送成功 返回:"+result);
}
});

调用获取图片:
AjaxUtil.getInstance().GetImage("image url 地址", new AjaxUtil.AnsyImageCallback() {
@Override
public void AnsyImageLoader(Bitmap bitmap, String Url) {
//imageview.setImageBitmap(bitmap);
}
});
 --------------------------FileUtils android 通用路径解析类--------------------------
package com.example.xxxxxx.product;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {
public static String getPath(final Context context, final Uri uri) {

final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];

if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}

// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {

final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];

Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}

final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};

return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}

return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {

Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};

try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}
 
 

posted on 2020-03-18 13:46  淡然→笑  阅读(778)  评论(0编辑  收藏  举报