1. 程式人生 > >Retrofit(預備篇)、Retrofit+OkHttp實現簡單的Get與Post請求

Retrofit(預備篇)、Retrofit+OkHttp實現簡單的Get與Post請求

在上面兩講中學習了OkHttp的使用,OkHttp還是很強大的。

而本人更喜歡Retrofit+OkHttp結合來實現網路請求,Retrofit使用註解,更加清晰與明瞭。下面用Retrofit實現簡單的Get與Post請求。

一、伺服器端

新建OkHttpServer伺服器專案,Tomcat伺服器具體配置可以參考搭建本地Tomcat伺服器及相關配置 。在專案下新建PostAndGetServlet:最後啟動伺服器。

@WebServlet("/PostAndGetServlet")
public class PostAndGetServlet extends HttpServlet {
    private
static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public PostAndGetServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected
void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); String userName = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("userName=="
+userName+"==password=="+password); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.print("Get收到資訊"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doPost"); String userName = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("userName=="+userName+"==password=="+password); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.print("Post收到資訊"); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

二、Android端

1.build.gradle引入相應的jar包

  compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:24.1.1'
    testCompile 'junit:junit:4.12'
    compile files('libs/gson-2.4.jar')
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.0.0'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.在layout檔案中增加兩個按鈕:

   <Button
        android:id="@+id/refrofit_get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="GET_TEST" />


    <Button
        android:id="@+id/refrofit_post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="POST_TEST" />
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

在Activity中例項化兩個按鈕,並設定點選事件。程式碼就不貼了。

3.新建RetrofitUtil類,編寫以下兩個方法:

public class RetrofitUtil {

//電腦端cmd輸入ipconfig獲取ip
   public static String baseUrl = "http://192.168.0.100:8080/OkHttpServer/";

   public static  Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
           .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    //返回string型別,如果返回的是json型別:addConverterFactory(GsonConverterFactory.create())    
        .addConverterFactory(ScalarsConverterFactory.create())
           .baseUrl(baseUrl);


    private static OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000, TimeUnit.MILLISECONDS)
            .readTimeout(10000,TimeUnit.MILLISECONDS)
            .writeTimeout(10000,TimeUnit.MILLISECONDS).build();

//get請求
    public static void testGet(){
        InterfaceRetrofit.GetPetrofit getPetrofit = retrofitBuilder.build().create(InterfaceRetrofit.GetPetrofit.class);
        getPetrofit.getTest("xiaohong","123").enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {

                Log.i("test",response.body().toString());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

//post請求
    public static void testPost(){
        InterfaceRetrofit.PostRetrofit postRetrofit = retrofitBuilder.build().create(InterfaceRetrofit.PostRetrofit.class);
        postRetrofit.postTest("xiaoqing","456").enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("test",response.body().toString());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

4.Retrofit的呼叫是通過介面實現的,上面的get與post請求也是,相應介面如下:

public interface InterfaceRetrofit {

    public interface GetPetrofit {
        @GET("PostAndGetServlet")
        Call<String> getTest(@Query("username") String username, @Query("password") String password);
    }


    public interface PostRetrofit{
        @FormUrlEncoded
        @POST("PostAndGetServlet")
        Call<String> postTest(@Field("username") String username, @Field("password")String password);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

5.為兩個按鈕新增點選事件,分別新增以上兩個方法。最後別忘了相應的許可權:

    <uses-permission android:name="android.permission.INTERNET"/>
  • 1

6.Android 端相關log:

07-03 20:41:07.772 25048-25048/com.huang.retrofit I/test: Get收到資訊
07-03 20:41:16.952 25048-25048/com.huang.retrofit I/test: Post收到資訊
  • 1
  • 2

伺服器端log:

轉自:https://blog.csdn.net/Gary__123456/article/details/74275974