本文共 7839 字,大约阅读时间需要 26 分钟。
本文将展示如何通过Android开发框架(比如Android Studio)使用Retrofit库进行多种网络请求,包括简单键值对、JSON数据、文件上传等功能。通过示例代码和解释,帮助开发者理解如何在实际应用中实现不同类型的网络请求。
首先需要确保在Android开发环境中已经准备好:
INTERNET
)public class Student { private String name; private String age; public Student(String name, String age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; }}
public interface ResponseInfoApi { // 发送GET请求获取测试数据 @GET("get") CallgetTestData(); // 发送POST请求测试键值对 @FormUrlEncoded @POST("post") Call postKeyValue( @Field("name") String name, @Field("age") String age ); // 发送POST请求测试参数化的键值对 @FormUrlEncoded @POST("post") Call postKeyValueMap( @FieldMap() Map map ); // 发送POST请求测试JSON数据 @Headers("Content-Type: application/json") @POST("post") Call postJson( @Body RequestBody body ); // 发送POST请求测试多个文件 @Multipart @POST("post") Call upload( @Part MultipartBody.Part file ); // 发送POST请求测试多张图片 @Multipart @POST("post") Call uploadFiles( @PartMap() Map maps );}
public void getTestData() { Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://httpbin.org/") .addConverterFactory(GsonConverterFactory.create()) .build(); ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class); Callcall = responseInfoApi.getTestData(); call.enqueue(new Callback () { @Override public void onResponse(Call call, Response response) { Log.d(TAG, "GET请求成功,响应内容为:" + response.body().string()); } @Override public void onFailure(Call call, Throwable t) { Log.d(TAG, "GET请求失败:" + t.getCause().getMessage()); } });}
public void postKeyValue(String name, String age) { Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://httpbin.org/") .addConverterFactory(GsonConverterFactory.create()) .build(); ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class); Callcall = responseInfoApi.postKeyValue( "猪八戒", "18" ); call.enqueue(new Callback () { @Override public void onResponse(Call call, Response response) { Log.d(TAG, "POST键值对请求成功,响应内容为:" + response.body().string()); } @Override public void onFailure(Call call, Throwable t) { Log.d(TAG, "POST键值对请求失败:" + t.getCause().getMessage()); } });}
public void postJson() { Student student = new Student("猪八戒", "20"); Gson gson = new Gson(); String json = gson.toJson(student); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://httpbin.org/") .addConverterFactory(GsonConverterFactory.create()) .build(); ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class); RequestBody requestBody = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), json ); Callcall = responseInfoApi.postJson(requestBody); call.enqueue(new Callback () { @Override public void onResponse(Call call, Response response) { try { String bodyStr = response.body().string(); Log.d(TAG, "JSON数据请求成功,响应内容为:" + bodyStr); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call call, Throwable t) { Log.d(TAG, "JSON数据请求失败:" + t.getCause().getMessage()); } });}
public void uploadFiles(Bitmap bitmap1, Bitmap bitmap2) { try { // 生成文件路径 File imgFile = new File(getCacheDir(), "imgFile"); // 复制Bitmap到文件 for (Bitmap bitmap : Arrays.asList(bitmap1, bitmap2)) { File imgFile = new File(getCacheDir(), "imgFile" + i); FileOutputStream fileOutputStream = new FileOutputStream(imgFile); bitmap(compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)); fileOutputStream.close(); } // 使用Retrofit上传文件 Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://httpbin.org/") .addConverterFactory(GsonConverterFactory.create()) .build(); ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class); // 创建Rest请求 RequestBody_EMIT requestFile1 = RequestBody.create( MediaType.parse("multipart/form-data"), imgFile1 ); RequestBody_EMIT requestFile2 = RequestBody.create( MediaType.parse("multipart/form-data"), imgFile2 ); HashMapmap = new HashMap<>(); map.put("actimg", requestFile1); map.put("listImg", requestFile2); Call call = responseInfoApi.uploadFiles(map); call.enqueue(new Callback () { @Override public void onResponse(Call call, Response response) { String bodyStr = response.body().string(); Log.d(TAG, "多文件上传请求成功,响应内容为:" + bodyStr); } @Override public void onFailure(Call call, Throwable t) { Log.d(TAG, "多文件上传请求失败:" + t.getCause().getMessage()); } }); } catch (FileNotFoundException e) { e.printStackTrace(); }}
public void upload(File file) { try { // 创建文件流 File imgFile = file; FileOutputStream fileOutputStream = new FileOutputStream(imgFile); // 将Bitmap压缩并保存到文件中 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.logo); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream); fileOutputStream.close(); // 使用Retrofit上传文件 Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://httpbin.org/") .addConverterFactory(GsonConverterFactory.create()) .build(); ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class); RequestBody requestFile = RequestBody.create( MediaType.parse("multipart/form-data"), imgFile ); MultipartBody.Part body = MultipartBody.Part.createFormData("actimg", imgFile.getName(), requestFile); Callcall = responseInfoApi.upload(body); call.enqueue(new Callback () { @Override public void onResponse(Call call, Response response) { String bodyStr = response.body().string(); Log.d(TAG, "文件上传请求成功,响应内容为:" + bodyStr); } @Override public void onFailure(Call call, Throwable t) { Log.d(TAG, "文件上传请求失败:" + t.getCause().getMessage()); } }); } catch (FileNotFoundException e) { e.printStackTrace(); }}
以上示例展示了Retrofit在Android平台上如何实现多种网络请求包括GET、POST、JSON、文件上传等功能。通过灵活配置Retrofit,我们可以轻松实现对不同接口的调用,每个请求都可以单独配置参数和行为。项目中需要注意权限声明、数据格式转换等细节,以确保应用能够顺利连接到目标服务器并处理返回数据。
如果您希望了解更多Retrofit的高级功能或遇到具体问题,可以在项目开发过程中查阅相关文档或社区资源。记住,每个网络请求都需要谨慎处理,以确保最佳的用户体验和可靠的服务器通信。
转载地址:http://wbfcz.baihongyu.com/