Android Retrofit2網(wǎng)路編程實(shí)現(xiàn)方法詳解
Android里面本身有OKHttp,不過(guò)不是很好用,這里就用Retrofit2,簡(jiǎn)單好用。
首先,需要加入網(wǎng)絡(luò)權(quán)限:
<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’
這時(shí)準(zhǔn)備工作做完了。
先創(chuàng)建一個(gè)接口文件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外的最后一個(gè)路徑,可以理解為 IP+getmacaddress
這里用的是POST請(qǐng)求方式,@Field('mobile')為請(qǐng)求接口的參數(shù)。
寫(xiě)一個(gè)實(shí)體類模型,用來(lái)匹配接收的數(shù)據(jù)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>() {@Overridepublic 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 可以同時(shí)操作序列化數(shù)據(jù)javabean和header */}@Overridepublic 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>() {@Overridepublic 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 可以同時(shí)操作序列化數(shù)據(jù)javabean和header */}@Overridepublic 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 其實(shí)就是 :http://115.29.190.99/api/meta/getmacaddress 請(qǐng)求的全路徑。
兩種方式:
TestCall2 是直接接收接收返回json的數(shù)據(jù)。
TestCall3 是用模型接收返回的json數(shù)據(jù)。
輸出結(jié)構(gòu)為:

代碼
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. uni-app結(jié)合PHP實(shí)現(xiàn)單用戶登陸demo及解析2. ASP動(dòng)態(tài)include文件3. 如何用Python一次性下載抖音上音樂(lè)4. JavaScript實(shí)現(xiàn)組件化和模塊化方法詳解5. ASP.NET MVC使用異步Action的方法6. 概述IE和SQL2k開(kāi)發(fā)一個(gè)XML聊天程序7. 網(wǎng)頁(yè)中img圖片使用css實(shí)現(xiàn)等比例自動(dòng)縮放不變形(代碼已測(cè)試)8. 詳解瀏覽器的緩存機(jī)制9. jsp實(shí)現(xiàn)登錄驗(yàn)證的過(guò)濾器10. 刪除docker里建立容器的操作方法

網(wǎng)公網(wǎng)安備