栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

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

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

在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 TestCall2(@Field("mobile") String mobile);

  @FormUrlEncoded
  @POST("getmacaddress")
  Call 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 call = service.TestCall2("13296540788");
    call.enqueue(new Callback() {
 @Override
 public void onResponse(Call call, Response response) {
   // Get result bean from response.body()
   // List 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);
   
 }

 @Override
 public void onFailure(Call 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 call = service.TestCall3("13296540788");
      call.enqueue(new Callback() {
 @Override
 public void onResponse(Call call, Response response) {
   // Get result bean from response.body()
   // List 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);
   
 }

 @Override
 public void onFailure(Call 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数据。

输出结构为:

代码

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/153667.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号