Retrofit网络请求参数注解Json格式和form-data格式提交数据(实用)

Retrofit 以Json格式提交数据 (模拟登录功能)

1、ApiService

/**
* 登录
*/
@Headers("Content-Type:application/json")
@POST("user/login")
Observable login(@Body RequestBody requestBody);

2、创建一个Bean类

public class UserBean {
private String nickname;
private String password;
public UserBean(String nickname, String password) {
this.nickname = nickname;
this.password = password;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

3、将Bean类通过Gson转为json体

Gson gson = new Gson();
HashMap map = new HashMap<>();
map.put("nickname", "123456");
map.put("password, "abcdefg");
String jsonBody = gson.toJson(map);
// 此时的jsonBody打印出来的结果
// {"password":"abcdefg","nickname":"123456"}

4、Retrofit请求头是否携带 如果请求带请求头 用方法一,如果不带请求头 用方法二,请求头需要添加的数据根据需求自行添加

1、不带请求头
private void useRetrofit(String url) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
apiServices = retrofit.create(ApiService.class);
}
2、带请求头
private void useHeaderRetrofit(String url) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.addHeader("Content-Type", "application/json;charset=utf-8")
.build();
return chain.proceed(request);
}
});
OkHttpClient client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
apiServices = retrofit.create(ApiService.class);
}

5、网络请求的代码

RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), requestBody);
Observable responseBodyObservable = apiServices.login(body);
responseBodyObservable.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.d("TAG", "e:" + e);
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
Log.d("TAG", string);
callBack.onSuccess((T) string);
} catch (IOException e) {
e.printStackTrace();
}
}
});

Retrofit 以form-data格式提交数据 (模拟登录功能)

1、ApiService

1、当数据量大的情况下用方法1 推荐此方法 处理数据时方便一些
/**
* 登录
/
@Multipart
@POST("users/login")
Observable phoneLogin(@PartMap Map requestBodyMap);
2、当数据量小的情况下用方法2
/
*
* 登录
*/
@Multipart
@POST("users/login")
Call phoneLogin(@Part("nickname") RequestBody username, @Part("password") RequestBody password);

2、转为form-data

/**
* 转换为 form-data
*
* @param requestDataMap
* @return
*/
public static Map generateRequestBody(Map requestDataMap) {
Map requestBodyMap = new HashMap<>();
for (String key : requestDataMap.keySet()) {
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
requestDataMap.get(key) == null ? "" : requestDataMap.get(key));
requestBodyMap.put(key, requestBody);
}
return requestBodyMap;
}

3、Retrofit请求头是否携带 如果请求带请求头 用方法一,如果不带请求头 用方法二

1、不带请求头
private void useRetrofit(String url) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
apiServices = retrofit.create(ApiService.class);
}
2、带请求头
private void useHeaderRetrofit(String url) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.addHeader("Content-Type", "application/json;charset=utf-8")
.build();
return chain.proceed(request);
}
});
OkHttpClient client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
apiServices = retrofit.create(ApiService.class);
}

4、网络请求的代码

Map formMaildata = new HashMap<>();
formMaildata.put("nickname", "123456");
formMaildata.put("password", "abcdef");
Map stringRequestBodyMap = generateRequestBody(formMaildata);
//此时stringRequestBodyMap打印出来的结果
//{password=abcdef, nickname=123456}
Observable responseBodyObservable = apiServices.login(stringRequestBodyMap);
responseBodyObservable.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.d("TAG", "e:" + e);
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
Log.d("TAG", string);
// callBack.onSuccess((T) string);
} catch (IOException e) {
e.printStackTrace();
}
}
});

我总结的不是很全,这位博主介绍的十分详细;超级实用

https://blog.csdn.net/guohaosir/article/details/78942485

你可能感兴趣的:(Retrofit网络请求参数注解Json格式和form-data格式提交数据(实用))