Java 通过改装实现最小的post请求
我正在尝试了解改型,因为它似乎解决了我目前在JSON请求和处理方面遇到的许多问题 首先也是最重要的一点是,我知道我们使用的方法是在接口内部定义的,在发出简单的请求以获取数据的同时,根据著名的github示例指定要从url检索的内容以及所有必要的端点非常简单 因此,如果我们从github api检索信息,我们将首先创建所有必要的pojo模型等,然后将接口定义为:Java 通过改装实现最小的post请求,java,android,json,http,retrofit2,Java,Android,Json,Http,Retrofit2,我正在尝试了解改型,因为它似乎解决了我目前在JSON请求和处理方面遇到的许多问题 首先也是最重要的一点是,我知道我们使用的方法是在接口内部定义的,在发出简单的请求以获取数据的同时,根据著名的github示例指定要从url检索的内容以及所有必要的端点非常简单 因此,如果我们从github api检索信息,我们将首先创建所有必要的pojo模型等,然后将接口定义为: public interface GithubService { @GET("users/{username}") Ob
public interface GithubService {
@GET("users/{username}")
Observable<Github>getGithHubUser(@Path("username")String userName);
}
基本上,为了从服务器获得任何响应,我一直在使用简单的okhttp:
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(CREATE_MEDIA_TYPE, "data={\"process\":\"procesNumber\", \"phone\":\"123456\"}");
String ALLWAYS_API = "http://something something bla bla";
Request request = new Request.Builder()
.url("https://blablabla")
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
... etc etc etc
}
据我所知,我甚至需要创建一个pojo类来表示需要发送到改造的数据,大致如下:
public class DataRequest {
final String proces;
final String phone;
DataRequest(String process, String phone) {
this.process = process;
this.phone = phone;
}
}
这将符合发送到请求的信息,但我如何将其解析到接口实现中呢
interface DataService {
@Post(not a clue what to place here)
DataRequest postJson(@Body how?)
}
我该如何将其添加到改装生成器中?我使用的例子来自于网络上的不同论坛以及其他用户提出的其他问题,这一个特别有助于理解一些事情:但我仍然不明白所有事情的进展,其他一些问题和例子对于我需要做的事情来说太复杂了 好的,为了给任何想这么做的人留下答案。默认情况下,改型附带了许多实用程序,它们以JSON的形式处理数据的传递,但在本例中,我传递的是一个字符串,它看起来像一个名为data的标记内的JSON……我知道 但是,为了向面临类似问题的人们回答这个问题,为了传递字符串,我们需要导入标量转换器,就像我们需要导入gson转换器来使用改装服务一样:
compile 'com.squareup.retrofit2:converter-scalars:2.0.2'
之后,我们的服务可以处理为:
public interface CreateService {
@Headers({ "Content-Type: application/x-www-form-urlencoded;charset=UTF-8"})
@POST("your/post/path/goes/here")
Call<String> getStringScalar(@Body String body);
}
公共接口创建服务{
@标题({“内容类型:application/x-www-form-urlencoded;charset=UTF-8”})
@POST(“您的/帖子/路径/前往/此处”)
调用getStringScalar(@Body-String-Body);
}
我在一个单独的文件中编写服务生成器,在这种情况下,整个过程可以这样使用:
public class ServiceGeneratorWithScalarConvertor {
private static final String API_BASE_URL = "your/base/url/goes/here";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// basically, this code is the same as the one from before with the added instance of creating and making use of the scalar converter factory.....scratch that i took it off
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
builder.client(httpClient.build());
Retrofit retrofit = builder.build();
return retrofit.create(serviceClass);
}
}
带有CalarConvertor的公共类ServiceGenerator{
私有静态最终字符串API\u BASE\u URL=“your/BASE/URL/goes/here”;
私有静态OkHttpClient.Builder httpClient=new OkHttpClient.Builder();
//基本上,这段代码与以前的代码相同,添加了创建和使用标量转换器工厂的实例……我去掉了它
私人静态改装=
新的改型.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
公共静态S createService(类serviceClass){
builder.client(httpClient.build());
改装改装=builder.build();
返回改装。创建(serviceClass);
}
}
从那里,我们可以使用此特定方法访问结果(我在我的主要活动中使用此方法:
public void retroFitCreateAPIExample() {
CreateService service = ServiceGeneratorWithScalarConvertor.createService(CreateService.class);
String body = "data={\"process\":\"process1\",\"phone\":\"12345\"}";
Call<String> call = service.getStringScalar(body);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Log.d("Response Body>>>>>", response.body());
createR = new Gson().fromJson(response.body().toString(), CreateModels.class);
Log.d("CREATED RESPONSE",createR.getCreate().getStops().get(0).getCity());
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
public-void-example(){
CreateService=ServiceGeneratorWithCalarConvertor.CreateService(CreateService.class);
String body=“data={\'process\':\'process1\',\'phone\':\'12345\'”;
Call Call=service.getStringScalar(主体);
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
if(response.issusccessful()){
Log.d(“Response Body>>>”,Response.Body());
createR=new Gson().fromJson(response.body().toString(),CreateModels.class);
Log.d(“创建响应”,createR.getCreate().getStops().get(0.getCity());
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
}
});
}
实例被传递给使用标量转换器的服务生成器,post请求的主体被保存为一个简单字符串(如接口中指定的)我们可以根据需要对响应执行任何操作。如果这确实是您的api所期望的,请更改您的api。@njzk2 man我希望我可以……我希望……我可以……第一件事是,您需要使用
@Field
注释发送数据=…
参数所包含的形状@Post
中的内容,这一点非常清楚在文档中明确指出了指向端点的路径。我尝试了@Field DataRequest data
。但是,我不确定Field
的对象是如何序列化的,因此您可能需要研究一下,我想您可以将调用声明为调用
,并跳过json部分的。
public class ServiceGeneratorWithScalarConvertor {
private static final String API_BASE_URL = "your/base/url/goes/here";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// basically, this code is the same as the one from before with the added instance of creating and making use of the scalar converter factory.....scratch that i took it off
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
builder.client(httpClient.build());
Retrofit retrofit = builder.build();
return retrofit.create(serviceClass);
}
}
public void retroFitCreateAPIExample() {
CreateService service = ServiceGeneratorWithScalarConvertor.createService(CreateService.class);
String body = "data={\"process\":\"process1\",\"phone\":\"12345\"}";
Call<String> call = service.getStringScalar(body);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Log.d("Response Body>>>>>", response.body());
createR = new Gson().fromJson(response.body().toString(), CreateModels.class);
Log.d("CREATED RESPONSE",createR.getCreate().getStops().get(0).getCity());
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}