Retrofit2 post异步请求
2019-05-15 本文已影响0人
穿越平行宇宙
请求步骤:
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. 在主页面进行网络请求
MainActivity.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 java.util.HashMap;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button bt_categories;
private Button bt_list;
private Button bt_detail;
private TextView tv;
private RecyclerView rlv;
private Retrofit mRetrofit;
private ApiServer mApiServer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
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对象
Call<ResponseBody> call = mApiServer.getCategories("be3ac46843914f5cbe875defccd8f392");
//4.Call对象执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String request = response.body().string();
tv.setText(request);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
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.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();
final RequestBody requestBody = RequestBody.create(mediaType, str);
//3.获取到call 对象
Call<ResponseBody> list = mApiServer.getList(requestBody);
//4.call对象执行请求
list.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String string = response.body().string();
tv.setText(string);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
break;
case R.id.bt_detail:
//1.创建Retrofit对象
mRetrofit = new Retrofit.Builder()
.baseUrl(ApiServer.NEWS_URL)
.build();
//2.获取到ApiServer接口服务的对象
mApiServer = mRetrofit.create(ApiServer.class);
Map<String, Object> map = new HashMap<>();
map.put("newsId","82264991a5932770734bbd386aebedf6");
//3.获取到call 对象
Call<ResponseBody> detail = mApiServer.getDetail("be3ac46843914f5cbe875defccd8f392","82264991a5932770734bbd386aebedf6");
//4.call对象执行请求
detail.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String string = response.body().string();
tv.setText(string);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
break;
}
}
}
3. 布局文件
activity_main.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