Android Retrofit2는 사진, get 요청,post 요청을 업로드합니다.

7802 단어
다음은 GitHub 주소입니다. 그중에 사진을 올린 데모와 Retrofit 연합 OKHttp get과post에 대한 데모(rxjava, 동적 불러오기 권한과 관련된 간단한 사용)는 아래에서 흥미로운 것을 보여 주지 않습니다.https://github.com/zzzzzjson/retrofitDemo
그림을 올립니다. 이것은 프로젝트의build입니다.그레이드 안에 바로 붙이면 OK.
ext {
    // Sdk and tools
    minSdkVersion = 19
    targetSdkVersion = 26
    compileSdkVersion = 26
    buildToolsVersion = '26.0.2'
    //support  
    supportVersion = '27.1.0'
    constraintLayout = '1.0.2'
    junit = '4.12'
    testRunner = '1.0.1'
    espressoCore = '3.0.1'

    interceptor = "3.11.0"
    retrofit = '2.3.0'
    converterGson = '2.3.0'
    rxandroid = '1.2.1'
    rxjava = '1.3.0'
    rxbus = '1.0.6'
    adapterRxjava = '2.0.2'
}

의지하다
    implementation "com.squareup.okhttp3:logging-interceptor:$rootProject.interceptor"
    implementation "com.squareup.retrofit2:retrofit:$rootProject.retrofit"
    implementation "com.squareup.retrofit2:converter-gson:$rootProject.converterGson"
    implementation "io.reactivex:rxandroid:$rootProject.rxandroid"
    implementation "io.reactivex:rxjava:$rootProject.rxjava"
    implementation "com.hwangjr.rxbus:rxbus:$rootProject.rxbus"
    implementation "com.squareup.retrofit2:adapter-rxjava:$rootProject.adapterRxjava"
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

네트워킹 및 SD 카드 사용 권한
 
 

모든 인터페이스를 저장할 Contacts를 작성합니다.
//        
public class Contacts {
    //     
    public static final String BASE_URL="http://www.zhaoapi.cn/";
    //  
    public static final String USER_LOGIN="user/login";
    //    
    public static final String USER_INFO="user/getUserInfo";
    //    
    public static final String UP_LOAD_IMAGE="file/upload";
}

인터페이스를 처리하기 위해 Api를 쓰십시오
import java.util.Map;
import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;
import rx.Observable;
//      
public interface ApiService {
    @Multipart
    @POST
    Observable upLoadImage(@Url String url, @QueryMap Map map, @Part MultipartBody.Part file);
}

패키지 도구 클래스 업로드 이미지
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import soexample.umeng.com.retrofitimagedemo.ApiService;
import soexample.umeng.com.retrofitimagedemo.Contacts;

public class RetrofitUtils {

    private final OkHttpClient okHttpClient;
    private final ApiService apiService;

    private RetrofitUtils() {
       //     
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //                             
//              
        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                //                             
                //              
                .retryOnConnectionFailure(true)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                //  Gson  
                .addConverterFactory(GsonConverterFactory.create())
                //  RxJava
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(Contacts.BASE_URL)
                .client(okHttpClient)
                .build();
        apiService = retrofit.create(ApiService.class);
    }

    public static RetrofitUtils getInstance() {
        return RetroHolder.retro;
    }

    private static class RetroHolder {
        private static final RetrofitUtils retro = new RetrofitUtils();
    }

    public RetrofitUtils upLoadImage(String url, Map map, MultipartBody.Part body) {
        apiService.upLoadImage(url, map, body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
        return RetrofitUtils.getInstance();
    }

    private Observer observer = new Observer() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            if (httpListener != null) {
                httpListener.onError(e.getMessage());
            }
        }

        @Override
        public void onNext(ResponseBody responseBody) {
            if (httpListener != null) {
                try {
                    httpListener.onSuccess(responseBody.string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public interface HttpListener {
        void onSuccess(String jsonStr);

        void onError(String error);
    }

    private HttpListener httpListener;

    public void setHttpListener(HttpListener httpListener) {
        this.httpListener = httpListener;
    }
}

MainActivity
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import soexample.umeng.com.retrofitimagedemo.utils.RetrofitUtils;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.UpLoad_Btn)
    Button UpLoadBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.UpLoad_Btn)
    public void onViewClicked() {
        Map map=new HashMap<>();
        map.put("uid","23585");
        File file = new File(Environment.getExternalStorageDirectory() + "/Pictures/e.jpg");
        //      MultipartBody
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        RetrofitUtils.getInstance().upLoadImage(Contacts.UP_LOAD_IMAGE,map,body).setHttpListener(new RetrofitUtils.HttpListener() {
            @Override
            public void onSuccess(String jsonStr) {
                Log.e("onSuccess",jsonStr);
            }

            @Override
            public void onError(String error) {
                Log.e("onError",error);
            }
        });
    }
}

좋은 웹페이지 즐겨찾기