Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android Retrofit

Android Retrofit2网路编程实现方法详解

作者:手撕高达的村长

这篇文章主要介绍了Android Retrofit2网路编程实现方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Android里面本身有OKHttp,不过不是很好用,这里就用Retrofit2,简单好用。

首先,需要加入网络权限:

<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"/>

在build.gradle文件里加入引用包: Gson不用的话,就不需要添加

implementation 'com.squareup.okhttp3:okhttp:3.0.1'
implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

这时准备工作做完了。

先创建一个接口文件TestService

package controller.hzl.com.testclient;

import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.HTTP;
import retrofit2.http.POST;
import retrofit2.http.Path;
public interface TestService {
  @FormUrlEncoded
  @POST("getmacaddress")
  Call<ResponseBody> TestCall2(@Field("mobile") String mobile);

  @FormUrlEncoded
  @POST("getmacaddress")
  Call<MacAdress> TestCall3(@Field("mobile") String mobile);
}

这里的@POST("getmacaddress") 的getmacaddress 是URL除IP外的最后一个路径,可以理解为 IP+getmacaddress

这里用的是POST请求方式,@Field("mobile")为请求接口的参数。

写一个实体类模型,用来匹配接收的数据MacAdress

package controller.hzl.com.testclient;

public class MacAdress {
  private String resultMsg;

  public String getResultMsg() {
    return resultMsg;
  }

  public void setResultMsg(String resultMsg) {
    this.resultMsg = resultMsg;
  }

  public String getResultState() {
    return resultState;
  }

  public void setResultState(String resultState) {
    this.resultState = resultState;
  }

  public String getResultObj() {
    return resultObj;
  }

  public void setResultObj(String resultObj) {
    this.resultObj = resultObj;
  }

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }
  public String getDelta() {
    return delta;
  }
  public void setDelta(String delta) {
    this.delta = delta;
  }
  private String resultState;
  private String resultObj;
  private String message;
  private String delta;
}

最后主MainActivity

package controller.hzl.com.testclient;

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


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class MainActivity extends Activity {
  private Button button1;
  private Button button2;
  private Button button3;
  private Button button4;
  private Button button5;
  private Button button6;
  private Button button7;
  private Button button8;
  private ImageView image;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    button3 = (Button) findViewById(R.id.button3);
    button4 = (Button) findViewById(R.id.button4);
    button5 = (Button) findViewById(R.id.button5);
    button6 = (Button) findViewById(R.id.button6);
    button7 = (Button) findViewById(R.id.button7);
    button8 = (Button) findViewById(R.id.button8);
    image = (ImageView) findViewById(R.id.image); 
    
    button1.setOnClickListener(new OnClickListener(){
      @Override
      public void onClick(View arg0) {
        GitHubServiceTest();
      }     
    });

    button2.setOnClickListener(new OnClickListener(){
      @Override
      public void onClick(View arg0) {
        IWeatherGetTest();
      }
    });
  }
  
  private void GitHubServiceTest() {
    Retrofit retrofit = new Retrofit.Builder()
      .baseUrl("http://115.29.190.99/api/meta/")
      .addConverterFactory(GsonConverterFactory.create())
      .build();

    TestService service = retrofit.create(TestService.class);

    //https://api.github.com/users/octocat/repos
    Call<ResponseBody> call = service.TestCall2("13296540788");
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
          // Get result bean from response.body()
          // List<Repo> repos = response.body();
          System.out.println(response.code());
          try {
            System.out.println(response.body().string());
            String jsonstr = new String(response.body().bytes());
            System.out.println("jsonstr="+jsonstr);
          }catch (Exception e){

          }

          // Get header item from response
          String links = response.headers().get("Link");
          showlog("links="+links);
          /**
           * 不同于retrofit1 可以同时操作序列化数据javabean和header
          */
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable throwable) {
          throwable.printStackTrace();
          //showlog(throwable.getCause().toString());
        }
      });
  }

  private void IWeatherGetTest() {
    {
      Retrofit retrofit = new Retrofit.Builder()
          .baseUrl("http://115.29.190.99/api/meta/")
          .addConverterFactory(GsonConverterFactory.create())
          .build();

      TestService service = retrofit.create(TestService.class);

      //https://api.github.com/users/octocat/repos
      Call<MacAdress> call = service.TestCall3("13296540788");
      call.enqueue(new Callback<MacAdress>() {
        @Override
        public void onResponse(Call<MacAdress> call, Response<MacAdress> response) {
          // Get result bean from response.body()
          // List<Repo> repos = response.body();
          System.out.println(response.code());
          try {
            System.out.println(response.body().getResultObj());
            System.out.println(response.body().getResultState());
          }catch (Exception e){

          }

          // Get header item from response
          String links = response.headers().get("Link");
          showlog("links="+links);
          /**
           * 不同于retrofit1 可以同时操作序列化数据javabean和header
           */
        }

        @Override
        public void onFailure(Call<MacAdress> call, Throwable throwable) {
          throwable.printStackTrace();
          //showlog(throwable.getCause().toString());
        }
      });
    }
  }
  
  public static void showlog(String info) {
     System.out.print("Retrofit " + info + "\n");
  }
 

}

这里的baseUrl("http://115.29.190.99/api/meta/") 就是URL的前面路径,加上@POST("getmacaddress") 的getmacaddress 其实就是 :http://115.29.190.99/api/meta/getmacaddress 请求的全路径。

两种方式:

TestCall2 是直接接收接收返回json的数据。

TestCall3 是用模型接收返回的json数据。

输出结构为:

代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文