Retrofit2 post同步请求

请求步骤:

1,定义接口(封装URL地址和数据请求)
2,实例化Retrofit
3,通过Retrofit实例创建接口服务对象
4,接口服务对象调用接口中的方法,获取Call对象
5,Call对象执行请求(异步、同步请求)

目录

1. 定义接口

ApiServer.java

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Headers;
import retrofit2.http.POST;

/**
 * Created on 2019/5/15 14:56
 *
 * @author Q.PeterGuo
 * @version 1.0.0
 * @Description
 */
public interface ApiServer {

/*
    // 1.新闻类别
    // 请求头:Content-Type:application/x-www-form-urlencoded
    String newsCategories = "http://api.shujuzhihui.cn/api/news/categories?appKey=be3ac46843914f5cbe875defccd8f392";

    -----------------------------------------------------------------------------------------------------------------

    // 2.新闻列表
    // 请求头:Content-Type:application/json
    // 请求体:
    {
        "category": "要闻",
        "page": "1"
    }
    String newsList = "http://api.shujuzhihui.cn/api/news/list?appKey=be3ac46843914f5cbe875defccd8f392";

    -----------------------------------------------------------------------------------------------------------------

    // 3.新闻详情
    // 请求头(header):Content-Type:application/x-www-form-urlencoded
    // 请求内容(body):newsId:82264991a5932770734bbd386aebedf6
    {
       "appKey": "be3ac46843914f5cbe875defccd8f392",
       "newsId": "82264991a5932770734bbd386aebedf6"
    }

    String newsDetail = "http://api.shujuzhihui.cn/api/news/detail?appKey=be3ac46843914f5cbe875defccd8f392";
*/

    String NEWS_URL = "http://api.shujuzhihui.cn/api/news/";


    // 新闻类别列表
    @POST("categories")
    @FormUrlEncoded
    @Headers("Content-Type:application/x-www-form-urlencoded")
    Call<ResponseBody> getCategories(@Field("appKey") String appKey);


    // 新闻列表
    @POST("list?appKey=be3ac46843914f5cbe875defccd8f392")
    @Headers("Content-Type:application/json")
    Call<ResponseBody> getList(@Body RequestBody requestBody);


    // 新闻详情
    @POST("detail")
    @FormUrlEncoded
    @Headers("Content-Type:application/x-www-form-urlencoded")
    Call<ResponseBody> getDetail(@Field("appKey") String appKey, @Field("newsId") String newsId);


}

2. 在主页面进行网络请求

DemoActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.guolei.retrofit_demo.ok.ApiServer;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

// post 同步请求
public class DemoActivity extends AppCompatActivity implements View.OnClickListener {

    private Button bt_categories;
    private Button bt_list;
    private Button bt_detail;
    private TextView tv;
    private RecyclerView rlv;
    private static final String TAG = "DemoActivity";
    private Retrofit mRetrofit;
    private ApiServer mApiServer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);
        initView();

        // 如果出现Socket 超时,可以设置如下代码:增大客户端的超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", String
                .valueOf(10000));// (单位:毫秒)
        System.setProperty("sun.net.client.defaultReadTimeout", String
                .valueOf(10000)); // (单位:毫秒)

    }

    private void initView() {
        bt_categories = (Button) findViewById(R.id.bt_categories);
        bt_list = (Button) findViewById(R.id.bt_list);
        bt_detail = (Button) findViewById(R.id.bt_detail);
        tv = (TextView) findViewById(R.id.tv);
        rlv = (RecyclerView) findViewById(R.id.rlv);

        bt_categories.setOnClickListener(this);
        bt_list.setOnClickListener(this);
        bt_detail.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_categories:

                // 1.获取Retrofit 对象
                mRetrofit = new Retrofit.Builder()
                        .baseUrl(ApiServer.NEWS_URL)
                        .build();

                // 2.获取到ApiServer 接口服务对象
                mApiServer = mRetrofit.create(ApiServer.class);

                // 3.获取call对象
                final Call<ResponseBody> categories = mApiServer.getCategories("be3ac46843914f5cbe875defccd8f392");


                new Thread(new Runnable() { // 子线程执行
                    @Override
                    public void run() {

                        try {
                            // 4. call对象执行同步请求,请求数据在子线程中执行
                            Response<ResponseBody> execute = categories.execute();
                            final String result = execute.body().string();

                            runOnUiThread(new Runnable() {  // 主线程执行
                                @Override
                                public void run() {
                                    if (result != null){
                                        tv.setText(result); // 设置数据时,要在主线程中运行
                                    }
                                }
                            });
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }
                }).start();


                break;
            case R.id.bt_list:

                // 1.获取Retrofit 对象
                mRetrofit = new Retrofit.Builder()
                        .baseUrl(ApiServer.NEWS_URL)
                        .build();

                // 2.获取到ApiServer 接口服务对象
                mApiServer = mRetrofit.create(ApiServer.class);

                // 获取到请求类型(MediaType)
                MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");

                // 获取到请求内容
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("category", "要闻");
                    jsonObject.put("page", "1");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String str = jsonObject.toString();

                // 获取到请求体(RequestBody)
                final RequestBody requestBody = RequestBody.create(mediaType, str);

                // 3.获取call对象
                final Call<ResponseBody> list = mApiServer.getList(requestBody);

                // 4.call对象执行同步请求
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {

                            Response<ResponseBody> execute = list.execute();

                            final String result = execute.body().string();

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (result != null){
                                        tv.setText(result);
                                    }
                                }
                            });

                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();


                break;
            case R.id.bt_detail:

                // 1.获取Retrofit 对象
                mRetrofit = new Retrofit.Builder()
                        .baseUrl(ApiServer.NEWS_URL)
                        .build();

                // 2.获取到ApiServer 接口服务对象
                mApiServer = mRetrofit.create(ApiServer.class);

                // 3.获取到call对象
                final Call<ResponseBody> detail = mApiServer.getDetail("be3ac46843914f5cbe875defccd8f392", "82264991a5932770734bbd386aebedf6");

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            Response<ResponseBody> execute = detail.execute();
                            final String result = execute.body().string();

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    if (result != null){
                                        tv.setText(result);
                                    }

                                }
                            });



                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();


                break;
        }
    }
}

3. 布局文件

activity_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/bt_categories"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="新闻类别" />

        <Button
            android:id="@+id/bt_list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="新闻列表" />

        <Button
            android:id="@+id/bt_detail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="新闻详情" />


    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorPrimary" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </ScrollView>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/rlv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

运行结果如下:


retrofit_post请求.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容