android - 我无法使用 Volley 进行网络调用

标签 android json get android-volley

当我使用 jsonObject 请求进行网络调用时。我没有收到任何回复。我总是在我的 URL 之前收到 request=<[ ] 的 HTTP 响应。我也尝试过这些链接,但对我没有任何作用。

Android Volley double post 当有缓慢的请求时:

Source1 , source2 , Source 3

 package com.example.mts3.hammadnewsapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.ArrayList;

public class NewsDetailsActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    NewsAdapter adapter;
    ArrayList<NewsOpen> newsList =new ArrayList<>();
    Intent intent;
    TextView tv_newsheading;

    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    Context context;
    String DATA_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/getnewsfeeds?order=asc";

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

        Toolbar toolbar =  findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        newsList = new ArrayList<>();
        recyclerView = findViewById(R.id.rv_newsdetails);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new NewsAdapter(this, newsList);

        String string = (String) getText(R.string.random_text);

        newsList.add(new NewsOpen(R.drawable.hdr_bg_plain, "Chief Medical Officer", "10-11-2020", string));
//        newsList.add(new NewsOpen("image!!", "Chief Medical Officer", "10-11-2020", string));

        recyclerView.setAdapter(adapter);
        /*backgroundTask.getList(new BackgroundTask.arrayCallBack() {
            @Override
            public void onSuccess(ArrayList<Contact> contacts) {
                adapter = new RecyclerAdapter(contacts);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onFail(String msg) {
                // Do Stuff
            }
        });*/



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_news_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_share) {

            //Toast.makeText(NewsDetailsActivity.this, "Share menu clicked ", Toast.LENGTH_LONG).show();
            callApi();
            return true;
        }
        if (id == R.id.action_logout) {
            sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
            editor= sharedPreferences.edit();
            editor.putBoolean("Verified user",false);
            editor.commit();

            Toast.makeText(NewsDetailsActivity.this,"Logged out ",Toast.LENGTH_LONG).show();
            Intent intent=new Intent(NewsDetailsActivity.this,MainActivity.class);
            startActivity(intent);


            return true;
        }

        return super.onOptionsItemSelected(item);
        }

    private void callApi() {
       // new DefaultRetryPolicy(30000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
           // int x=3;// retry count
           // DefaultRetryPolicy defaultRetryPolicy=new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS*1,x,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        //DefaultRetryPolicy defaultRetryPolicy= new DefaultRetryPolicy(20 * 1000, 0, 1.0f);
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        //System.setProperty("http.keepAlive", "false");
        JsonObjectRequest jsonObject =new JsonObjectRequest(Request.Method.GET,DATA_URL, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.e("res",response.toString());

            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }

        });
        //int x=2;// retry count
        //jsonObject.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 48, x, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        //jsonObject.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 48,0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        //jsonObject.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0));
        //jsonObject.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        //jsonObject.setRetryPolicy(new DefaultRetryPolicy(0,-1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        /*jsonObject.setRetryPolicy(
                new DefaultRetryPolicy(
                        500000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
                )
        );*/
        //jsonObject.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        //new DefaultRetryPolicy(10000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        //jsonObject.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        //jsonObject.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        //int socketTimeout = 30000;//30 seconds - change to what you want
       // RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
       // jsonObject.setRetryPolicy(policy);
        int custom_timeout_ms = 10000;
        DefaultRetryPolicy policy = new DefaultRetryPolicy(custom_timeout_ms,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        jsonObject.setRetryPolicy(policy);
        requestQueue.add(jsonObject);

    }

}

Error Log for network call

最佳答案

另一种使用 StringRequest 获取 Json Response 的解决方案

  private void callApi() {
    RequestQueue mrequestQueue;
    StringRequest stringRequest;
    mrequestQueue = Volley.newRequestQueue(this);
    stringRequest = new StringRequest(Request.Method.GET, DATA_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {

                JSONObject jsonObject = new JSONObject(response);
                System.out.println("json"+jsonObject);


            } catch (JSONException e) {

                e.printStackTrace();
            }


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //Log.i(TAG, "Response: " + error.toString());

        }
    });
    mrequestQueue.add(stringRequest);


}

Output image

关于android - 我无法使用 Volley 进行网络调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47936955/

相关文章:

android - Eclipse/Android 原始 txt 文件错误 (Content is not allowed in prolog)

Grails g :paginate - Passing search parameters back to Controller

php - 通过在 url 中传递值在同一页面中从 mysql 执行两个查询

php - 如何从 URL 中删除特定的 $_GET 变量

android - 如何获取另一个模块中Application()类的引用?

android - 如何将 TestNG 集成到 Android 项目中?

Android - 返回 onActivityResult 的 Intent

java.lang.NullPointerException-Android 中的错误

json - 无效操作 : type interface {} does not support indexing

javascript - 如果对象包含 JavaScript 中的字母,如何返回对象