Retrofit 请求发送application/json或者application/x-www-form-urlencoded数据
时间: 2023-11-08 19:54:49 浏览: 43
在使用 Retrofit 发送请求时,可以通过设置请求头来指定发送的数据类型为 application/json 或者 application/x-www-form-urlencoded。下面是示例代码:
1. 发送 application/json 数据:
```java
// 创建 Retrofit 实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
// 创建服务接口
MyApiService apiService = retrofit.create(MyApiService.class);
// 构建请求体
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonBody);
// 发送请求
Call<ResponseBody> call = apiService.postData(requestBody);
call.enqueue(new Callback<ResponseBody>() {
// 处理响应
});
```
2. 发送 application/x-www-form-urlencoded 数据:
```java
// 创建 Retrofit 实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
// 创建服务接口
MyApiService apiService = retrofit.create(MyApiService.class);
// 创建表单数据
FormUrlEncodedRequestBod