retrofit --post请求
发布日期:2021-05-10 02:32:19 浏览次数:10 分类:精选文章

本文共 7839 字,大约阅读时间需要 26 分钟。

Android网络请求优化实例

本文将展示如何通过Android开发框架(比如Android Studio)使用Retrofit库进行多种网络请求,包括简单键值对、JSON数据、文件上传等功能。通过示例代码和解释,帮助开发者理解如何在实际应用中实现不同类型的网络请求。

1. 模拟数据及工具准备

首先需要确保在Android开发环境中已经准备好:

  • 工具:Android Studio IDE
  • :Retrofit及其必要的依赖(如GsonConverterFactory)
  • 权限:确保已经在AndroidManifest.xml中声明了必要的网络权限(如INTERNET

2. 学生数据模型

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;    }}

3. Retrofit代理接口定义

public interface ResponseInfoApi {    // 发送GET请求获取测试数据    @GET("get")    Call
getTestData(); // 发送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 );}

4. 各种网络请求实现

4.1 测试GET请求

public void getTestData() {    Retrofit retrofit = new Retrofit.Builder()        .baseUrl("http://httpbin.org/")        .addConverterFactory(GsonConverterFactory.create())        .build();    ResponseInfoApi responseInfoApi = retrofit.create(ResponseInfoApi.class);    Call
call = 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()); } });}

4.2 POST键值对请求

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);    Call
call = 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()); } });}

4.3 POST JSON数据请求

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    );    Call
call = 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()); } });}

4.4 模式多文件上传

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        );        HashMap
map = 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(); }}

4.5 单独文件上传

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);        Call
call = 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(); }}

5. 总结

以上示例展示了Retrofit在Android平台上如何实现多种网络请求包括GET、POST、JSON、文件上传等功能。通过灵活配置Retrofit,我们可以轻松实现对不同接口的调用,每个请求都可以单独配置参数和行为。项目中需要注意权限声明、数据格式转换等细节,以确保应用能够顺利连接到目标服务器并处理返回数据。

如果您希望了解更多Retrofit的高级功能或遇到具体问题,可以在项目开发过程中查阅相关文档或社区资源。记住,每个网络请求都需要谨慎处理,以确保最佳的用户体验和可靠的服务器通信。

上一篇:svn项目迁移
下一篇:系统震动,响铃,指示灯

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月01日 15时45分36秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章