1.导入依赖
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
implementation("com.squareup.retrofit2:converter-scalars:2.9.0")
implementation("com.squareup.okhttp3:logging-interceptor:3.14.+")
2.需要配置清单文件
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.OkHttp"
android:networkSecurityConfig="@xml/network_security_config">
android:name=".MainActivity"
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
android:authorities="${applicationId}.provider"
android:name="androidx.core.content.FileProvider"
android:grantUriPermissions="true">
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
3.网络权限和 provider
provider_paths.xml
"1.0" encoding="utf-8" ?>
network_security_config.xml
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
4.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
androidx.constraintlayout.widget.ConstraintLayout>
5.ApiService
package com.tiger.retrofel.api;
import okhttp3.MultipartBody;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Query;
public interface ApiService {
@Field("start") Integer start,
@Field("count") Integer count
@Part MultipartBody.Part part
6.权限工具类
package com.tiger.retrofel;
import android.app.Activity;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class PermissionUtil {
public static final String[] PERMISSIONS_EXTERNAL_STORAGE = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
public static final int PERMISSIONS_EXTERNAL_STORAGE_TAG = 1;
public static boolean checkPermission(Activity act, String[] permissions, int requestCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int check = PackageManager.PERMISSION_GRANTED;
for (String permission : permissions) {
check = ContextCompat.checkSelfPermission(act, permission);
if (check != PackageManager.PERMISSION_GRANTED) {
if (check != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(act, permissions, requestCode);
public static boolean checkGrant(int[] grantResults) {
if (grantResults != null) {
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED) {
7.Activity
package com.tiger.retrofel;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import com.tiger.retrofel.api.ApiService;
import com.tiger.retrofel.api.Subject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class MainActivity extends AppCompatActivity {
private OkHttpClient client;
private ApiService apiService;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
public void log(String message) {
}).setLevel(HttpLoggingInterceptor.Level.BASIC);
client = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.202.55:8999/")
.addConverterFactory(GsonConverterFactory.create())
apiService = retrofit.create(ApiService.class);
Button viewById = findViewById(R.id.upload);
viewById.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
private void syncRequest() {
Response
execute = apiService.test(0, 2).execute();
} catch (IOException e) {
throw new RuntimeException(e);
Map body = execute.body();
Log.i("ning", "run:response:" + body);
private void ayncRequest() {
apiService.test(0, 2).enqueue(new Callback
public void onResponse(Call {
public void onFailure(Call> call, Throwable t) {
private void showPhoto() {
if (PermissionUtil.checkPermission(this, PermissionUtil.PERMISSIONS_EXTERNAL_STORAGE, PermissionUtil.PERMISSIONS_EXTERNAL_STORAGE_TAG)) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,1);
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==1 && resultCode == Activity.RESULT_OK &&data!=null){
Uri selectedImage = data.getData();
String[] filePathColumns ={MediaStore.Images.Media.DATA};
Cursor query = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
int columnIndex = query.getColumnIndex(filePathColumns[0]);
String string = query.getString(columnIndex);
public void uploadFile(String path){
File file = new File(path);
RequestBody requestBody = RequestBody.create(MediaType.parse("image/jp"),file);
MultipartBody.Part part = MultipartBody.Part.createFormData("pic",file.getName(),requestBody);
apiService.upload(part).enqueue(new Callback>() {
public void onResponse(Call> call, Response> response) {
Log.d("ning",response.body().get("result").toString());
public void onFailure(Call> call, Throwable t) {
8.实体类
private String episodes_info;
private Boolean playable;