繁体   English   中英

从JSON响应改造中获取字符串数据

[英]Fetch string data from JSON response retrofit

我正在使用可以从服务器获取的JSON响应,一开始我必须登录我的应用程序,因此我使用以下api:

@Headers("Content-type: application/json")
    @POST("/v1/login")
    Call<Post> auth(@Body Post body);

还有我的POJO类:

public class Post {
    @SerializedName("username")
    private String username;
    @SerializedName("password")
    private String password;

    public Post(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername (String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

并在我的mainactivity类中将其初始化:

public void sendPost() {
        final EditText titleEt = findViewById(R.id.login);
        final EditText bodyEt = findViewById(R.id.password);
        final String a = titleEt.getText().toString().trim();
        final String b = bodyEt.getText().toString().trim();

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://server/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        APIService mAPIService = retrofit.create(APIService.class);
        //retrofit.create(APIService.class);

        mAPIService.auth(new Post(a, b)).enqueue(new Callback<Post>() {
            @Override
            public void onResponse(@NonNull Call<Post> call, @NonNull Response<Post> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(LoginActivity.this, "Post submitted to API.", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(LoginActivity.this, SecondScreen.class);
                    findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor("#1cd000"), PorterDuff.Mode.MULTIPLY);
                    startActivity(intent);
                    saveData();
                   /* try {
                        String responseString = String.valueOf(response.body());
                        TextView txt = findViewById(R.id.post);
                        txt.setText(responseString);
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }*/


                } else {
                    Toast.makeText(LoginActivity.this, "Unable to submit post to API.Error!!!", Toast.LENGTH_LONG).show();
                    findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.MULTIPLY);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Post> call, @NonNull Throwable t) {
                Toast.makeText(LoginActivity.this, "Unable to submit post to API.", Toast.LENGTH_LONG).show();

            }
        });
    }

如您所见,我评论了我试图从JSON响应中获取一些数据的评论,总的来说,我想从响应中获取访问令牌,并且如果可能的话,我也不想创建某些类来进行获取,因为我已经在MainActivity类上初始化了我的改造。 登录后也可以使用JSON获取我的已接收和已发送消息,但是我想将此数据插入到简单的listview中。 因此,我希望这个论坛的人能帮助我解决我的问题。 对不起,我英语可能不好。

您必须了解每个Retrofit请求都是异步的 ,这意味着最终将在您的应用程序运行时执行该请求。 您应该使用RxJava来帮助您,因为您应该用来观察需要从API获取的数据。

重要说明 :由于更新未在主线程中运行,因此在更新响应中更新UI可能会触发异常。

一些有用的链接来实现您所需要的:

https://www.toptal.com/android/functional-reactive-android-rxjava

https://www.journaldev.com/20433/android-rxjava-retrofit

https://medium.com/3xplore/handling-api-calls-using-retrofit-2-and-rxjava-2-1871c891b6ae

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM