• Retrofit


    1.导入依赖 

    1. //Retrofit 核心库
    2. implementation("com.squareup.retrofit2:retrofit:2.9.0")
    3. //响应数据自动序列化
    4. //JSON
    5. implementation("com.squareup.retrofit2:converter-gson:2.9.0")
    6. //String类型
    7. implementation("com.squareup.retrofit2:converter-scalars:2.9.0")
    8. //拦截器 logging
    9. implementation("com.squareup.okhttp3:logging-interceptor:3.14.+")

    2.需要配置清单文件

    1. "1.0" encoding="utf-8"?>
    2. <manifest xmlns:android="http://schemas.android.com/apk/res/android">
    3. <uses-permission android:name="android.permission.INTERNET"/>
    4. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    5. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    6. <application
    7. android:allowBackup="true"
    8. android:icon="@mipmap/ic_launcher"
    9. android:label="@string/app_name"
    10. android:roundIcon="@mipmap/ic_launcher_round"
    11. android:supportsRtl="true"
    12. android:theme="@style/Theme.OkHttp"
    13. android:networkSecurityConfig="@xml/network_security_config">
    14. <activity
    15. android:name=".MainActivity"
    16. android:exported="true">
    17. <intent-filter>
    18. <action android:name="android.intent.action.MAIN" />
    19. <category android:name="android.intent.category.LAUNCHER" />
    20. intent-filter>
    21. activity>
    22. <provider
    23. android:authorities="${applicationId}.provider"
    24. android:name="androidx.core.content.FileProvider"
    25. android:exported="false"
    26. android:grantUriPermissions="true">
    27. <meta-data
    28. android:name="android.support.FILE_PROVIDER_PATHS"
    29. android:resource="@xml/provider_paths"/>
    30. provider>
    31. application>
    32. manifest>

    3.网络权限和 provider

    provider_paths.xml

    1. "1.0" encoding="utf-8" ?>
    2. <paths>
    3. <external-path
    4. name="aaa"
    5. path="."/>
    6. paths>

    network_security_config.xml

    1. "1.0" encoding="utf-8"?>
    2. <network-security-config>
    3. <base-config cleartextTrafficPermitted="true" />
    4. network-security-config>

    4.xml

    1. "1.0" encoding="utf-8"?>
    2. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. xmlns:app="http://schemas.android.com/apk/res-auto"
    4. xmlns:tools="http://schemas.android.com/tools"
    5. android:layout_width="match_parent"
    6. android:layout_height="match_parent"
    7. tools:context=".MainActivity">
    8. <Button
    9. android:id="@+id/upload"
    10. android:layout_width="match_parent"
    11. android:layout_height="wrap_content"
    12. android:text="上传图片"
    13. app:layout_constraintBottom_toBottomOf="parent"
    14. app:layout_constraintEnd_toEndOf="parent"
    15. app:layout_constraintStart_toStartOf="parent"
    16. app:layout_constraintTop_toTopOf="parent" />
    17. androidx.constraintlayout.widget.ConstraintLayout>

    5.ApiService

    1. package com.tiger.retrofel.api;
    2. import java.util.List;
    3. import java.util.Map;
    4. import okhttp3.MultipartBody;
    5. import retrofit2.Call;
    6. import retrofit2.http.Field;
    7. import retrofit2.http.FormUrlEncoded;
    8. import retrofit2.http.GET;
    9. import retrofit2.http.Multipart;
    10. import retrofit2.http.POST;
    11. import retrofit2.http.Part;
    12. import retrofit2.http.Query;
    13. public interface ApiService {
    14. @POST("findList")
    15. @FormUrlEncoded
    16. Call> test(
    17. @Field("start") Integer start,
    18. @Field("count") Integer count
    19. );
    20. @POST("uploadPic")
    21. @Multipart
    22. Call> upload(
    23. @Part MultipartBody.Part part
    24. );
    25. }

    6.权限工具类

    1. package com.tiger.retrofel;
    2. import android.Manifest;
    3. import android.app.Activity;
    4. import android.content.pm.PackageManager;
    5. import android.os.Build;
    6. import androidx.core.app.ActivityCompat;
    7. import androidx.core.content.ContextCompat;
    8. public class PermissionUtil {
    9. public static final String[] PERMISSIONS_EXTERNAL_STORAGE = new String[]{
    10. Manifest.permission.READ_EXTERNAL_STORAGE,
    11. Manifest.permission.WRITE_EXTERNAL_STORAGE
    12. };
    13. public static final int PERMISSIONS_EXTERNAL_STORAGE_TAG = 1;
    14. //检查多个权限。返回true表示已完全启用权限,返回false 表示 未完全启用权限
    15. public static boolean checkPermission(Activity act, String[] permissions, int requestCode) {
    16. //Android 6.0之后开始采用动态权限管理
    17. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    18. int check = PackageManager.PERMISSION_GRANTED;
    19. for (String permission : permissions) {
    20. check = ContextCompat.checkSelfPermission(act, permission);
    21. if (check != PackageManager.PERMISSION_GRANTED) {
    22. break;
    23. }
    24. }
    25. //未开启该权限,则请求系统弹窗,好让用户选择 是否立即开启权限
    26. if (check != PackageManager.PERMISSION_GRANTED) {
    27. ActivityCompat.requestPermissions(act, permissions, requestCode);
    28. return false;
    29. }
    30. }
    31. return true;
    32. }
    33. public static boolean checkGrant(int[] grantResults) {
    34. if (grantResults != null) {
    35. for (int grantResult : grantResults) {
    36. if (grantResult != PackageManager.PERMISSION_GRANTED) {
    37. return false;
    38. }
    39. }
    40. return true;
    41. } else {
    42. return false;
    43. }
    44. }
    45. }

    7.Activity

    1. package com.tiger.retrofel;
    2. import androidx.annotation.Nullable;
    3. import androidx.appcompat.app.AppCompatActivity;
    4. import android.app.Activity;
    5. import android.content.Intent;
    6. import android.database.Cursor;
    7. import android.net.Uri;
    8. import android.os.Bundle;
    9. import android.provider.MediaStore;
    10. import android.util.Log;
    11. import android.view.View;
    12. import android.widget.Button;
    13. import com.tiger.retrofel.api.ApiService;
    14. import com.tiger.retrofel.api.Subject;
    15. import java.io.File;
    16. import java.io.IOException;
    17. import java.util.List;
    18. import java.util.Map;
    19. import okhttp3.MediaType;
    20. import okhttp3.MultipartBody;
    21. import okhttp3.OkHttpClient;
    22. import okhttp3.RequestBody;
    23. import okhttp3.logging.HttpLoggingInterceptor;
    24. import retrofit2.Call;
    25. import retrofit2.Callback;
    26. import retrofit2.Response;
    27. import retrofit2.Retrofit;
    28. import retrofit2.converter.gson.GsonConverterFactory;
    29. import retrofit2.converter.scalars.ScalarsConverterFactory;
    30. public class MainActivity extends AppCompatActivity {
    31. Retrofit retrofit;
    32. private OkHttpClient client;
    33. private ApiService apiService;
    34. @Override
    35. protected void onCreate(Bundle savedInstanceState) {
    36. super.onCreate(savedInstanceState);
    37. setContentView(R.layout.activity_main);
    38. HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
    39. @Override
    40. public void log(String message) {
    41. Log.i("TAG", message);
    42. }
    43. }).setLevel(HttpLoggingInterceptor.Level.BASIC);
    44. client = new OkHttpClient.Builder()
    45. .addInterceptor(httpLoggingInterceptor)
    46. .build();
    47. retrofit = new Retrofit.Builder()
    48. .baseUrl("http://192.168.202.55:8999/")
    49. .client(client)
    50. // .addConverterFactory(ScalarsConverterFactory.create())
    51. .addConverterFactory(GsonConverterFactory.create())
    52. .build();
    53. apiService = retrofit.create(ApiService.class);
    54. Button viewById = findViewById(R.id.upload);
    55. viewById.setOnClickListener(new View.OnClickListener() {
    56. @Override
    57. public void onClick(View v) {
    58. showPhoto();
    59. }
    60. });
    61. syncRequest();
    62. }
    63. //同步的请求
    64. private void syncRequest() {
    65. //同步
    66. new Thread(() -> {
    67. Response> execute = null;
    68. try {
    69. execute = apiService.test(0, 2).execute();
    70. } catch (IOException e) {
    71. throw new RuntimeException(e);
    72. }
    73. Map body = execute.body();
    74. Log.i("ning", "run:response:" + body);
    75. }).start();
    76. }
    77. //异步的请求
    78. private void ayncRequest() {
    79. //同步
    80. try {
    81. apiService.test(0, 2).enqueue(new Callback>() {
    82. @Override
    83. public void onResponse(Call> call, Response> response) {
    84. }
    85. @Override
    86. public void onFailure(Call> call, Throwable t) {
    87. }
    88. });
    89. } catch (Exception e) {
    90. e.printStackTrace();
    91. }
    92. }
    93. private void showPhoto() {
    94. if (PermissionUtil.checkPermission(this, PermissionUtil.PERMISSIONS_EXTERNAL_STORAGE, PermissionUtil.PERMISSIONS_EXTERNAL_STORAGE_TAG)) {
    95. //有权限
    96. // 跳转到系统相册,选择图片,并返回
    97. Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    98. startActivityForResult(intent,1);
    99. }
    100. }
    101. @Override
    102. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    103. super.onActivityResult(requestCode, resultCode, data);
    104. // Log.d("ning","进来了"+resultCode+":"+resultCode);
    105. //获取图片路径
    106. if (requestCode==1 && resultCode == Activity.RESULT_OK &&data!=null){
    107. Uri selectedImage = data.getData();
    108. String[] filePathColumns ={MediaStore.Images.Media.DATA};
    109. Cursor query = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
    110. query.moveToFirst();
    111. int columnIndex = query.getColumnIndex(filePathColumns[0]);
    112. String string = query.getString(columnIndex);
    113. Log.d("ning",string);
    114. uploadFile(string);
    115. query.close();
    116. }
    117. }
    118. public void uploadFile(String path){
    119. File file = new File(path);
    120. RequestBody requestBody = RequestBody.create(MediaType.parse("image/jp"),file);
    121. MultipartBody.Part part = MultipartBody.Part.createFormData("pic",file.getName(),requestBody);
    122. apiService.upload(part).enqueue(new Callback>() {
    123. @Override
    124. public void onResponse(Call> call, Response> response) {
    125. Log.d("ning",response.body().get("result").toString());
    126. }
    127. @Override
    128. public void onFailure(Call> call, Throwable t) {
    129. }
    130. });
    131. }
    132. }

    8.实体类

    1. public class Subject {
    2. private String episodes_info;
    3. private String rate;
    4. private Integer cover_x;
    5. private String title;
    6. private String url;
    7. private Boolean playable;
    8. private String cover;
    9. private String id;
    10. private Integer cover_y;
    11. private Boolean is_new;

  • 相关阅读:
    pycharm进阶使用学习
    一文理解深度学习框架中的InstanceNorm
    excel如何让线条消失,直接设置网格即可,碰到不方便的地方优先百度,再采取蛮干
    c++ chrono
    代码随想录算法训练营第六十天| 739.每日温度 、496.下一个更大元素 I
    React 中 useEffect
    荣电集团与钕希科技签署全面战略合作
    构建 JavaScript ChatGPT 插件
    opencv-python 车牌检测和识别
    关于SRE在金融行业落地的探讨
  • 原文地址:https://blog.csdn.net/qq_53374893/article/details/136625390