如何获得服务器的响应?

时间:2019-04-21 19:51:06

标签: java android android-asynctask android-volley

我正在编写一个带有休息API请求的类(Yandex磁盘)。我使用凌空抽射,但从中得到回应确实有一些问题。您可以检查其余的API here

我使用排球,但可以在调试器中获得响应,但不能在Activity中得到响应。

这是我的Requests

class Requests {
    private String response_of_server, token;
    private String url = "https://cloud-api.yandex.net/v1/disk";
    private Context context;

    Requests (String token, Context context) {
        this.token = token;
        this.context = context;
    }

    private void set_response_of_server(String response) {
        this.response_of_server = response;
    }

    String get_response() {
        return response_of_server;
    }

    void get_metadata_of_user() {

        try {
            /*Request*/

            RequestQueue queue = Volley.newRequestQueue(this.context);


            Response.ErrorListener error_listener = new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            };
            Response.Listener<String> response_listener = new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    set_response_of_server(response);
                }
            };

            StringRequest getRequest = new StringRequest(Request.Method.GET, url+"?fields=user", response_listener, error_listener) {
                @Override
                public Map<String, String> getHeaders() {
                    Map<String, String>  params = new HashMap<>();
                    params.put("Host", "cloud-api.yandex.net");
                    params.put("Authorization", token);
                    return params;
                }
            };
            queue.add(getRequest);
            /*Request end*/

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

还有MainActivity,我想在此回复。

public class MainActivity extends AppCompatActivity {

    private final String ID_OF_APP = "Your token of app";
    private final String URL_FOR_CODE_QUERY = "https://oauth.yandex.com/authorize?response_type=token&client_id=" + ID_OF_APP;
    private String SAVED_TOKEN = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn_get_code = findViewById(R.id.btn_get_code); // send to get code page (yandex)
        btn_get_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(URL_FOR_CODE_QUERY));
                    startActivity(i);
            }
        });

        Button btn_sign_in = findViewById(R.id.btn_sign_in);
        btn_sign_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText code_field = findViewById(R.id.code_field);
                String token = code_field.getText().toString();
                save_token(token);
                try {
                    if(check_token()) {
                        //Toast.makeText(MainActivity.this, "You are successfully signed in", Toast.LENGTH_SHORT).show();
                        // TODO change activity
                    }
                    else {}
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //Toast.makeText(MainActivity.this, "Something went wrong. Please, check your connection and try again later", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void save_token(String token) {
        SharedPreferences sPref = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor ed = sPref.edit();
        ed.putString(SAVED_TOKEN, token);
        ed.apply();
    }

    private String load_token() {
        SharedPreferences sPref = getPreferences(MODE_PRIVATE);
        return sPref.getString(SAVED_TOKEN, "");
    }

    private boolean check_token() throws InterruptedException {
        String token = load_token();
        String result;
        Requests request = new Requests(token, this);
        request.get_metadata_of_user();
        result = request.get_response();
        Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
        return !(result.equals("-1"));
    }
}
现在,

check_token()函数应该只是随服务器的响应而改变。但是,我无法从服务器返回Toast或任何响应。

1 个答案:

答案 0 :(得分:1)

您有一个<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.6/ScrollMagic.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.2/TweenMax.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.6/plugins/jquery.ScrollMagic.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.6/plugins/animation.gsap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.6/plugins/debug.addIndicators.min.js"></script> <div></div> <h1 id="title">Hello World !</h1> <div></div>类,该类具有调用服务器API Requests的功能。因此,在Asynchronous函数中调用result之后,您不会立即得到request.get_metadata_of_user();

因此,我建议您像下面这样修改check_token()类。

Request

现在public class Requests { private String response_of_server, token; private String url = "https://cloud-api.yandex.net/v1/disk"; private Context context; private HttpListener listener; // Add a listener to get the callback functionality Requests (String token, Context context, HttpListener listener) { this.token = token; this.context = context; this.listener = listener; // initialize the listener here } private void set_response_of_server(String response) { this.response_of_server = response; listener.onResponseReceived(response); // Send the response back to the calling class } String get_response() { return response_of_server; } void get_metadata_of_user() { try { RequestQueue queue = Volley.newRequestQueue(this.context); Response.ErrorListener error_listener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }; Response.Listener<String> response_listener = new Response.Listener<String>() { @Override public void onResponse(String response) { set_response_of_server(response); } }; StringRequest getRequest = new StringRequest(Request.Method.GET, url+"?fields=user", response_listener, error_listener) { @Override public Map<String, String> getHeaders() { Map<String, String> params = new HashMap<>(); params.put("Host", "cloud-api.yandex.net"); params.put("Authorization", token); return params; } }; queue.add(getRequest); } catch (Exception e) { e.printStackTrace(); } } } 类可能如下所示。创建HttpListener并添加以下代码以将其创建为接口。

HttpListener.java

因此,您需要像下面这样在public interface HttpListener { public void onResponseReceived(); } 中实现此interface

MainActivity

请注意,该代码未经测试。请根据您的要求进行修改。我希望这可以帮助您理解问题。