Android JSON Volley не анализирует WordPress JSON Api - PullRequest
0 голосов
/ 30 октября 2018

Привет, ребята, я использовал RecyclerViewer для анализа данных JSON с помощью Volley, я получил его на работу. Моя единственная проблема сейчас - это анализ json из URL JSON API WordPress.

Если я создаю файл json на моем сервере и узнаю, что он работает нормально. Даже с теми же данными, что и в URL, сгенерированном WordPress

Я хочу сказать, что Wordpress Json предоставляет различные элементы управления кэшем или что-то в этом роде.

Я предпочитаю хранить данные и URL в безопасности. Но если кто-то может помочь мне выяснить, почему код, который я собираюсь предоставить ниже, не работает

Json Headers Wordpress Request

AnswerHeaders

X-Firefox-Spdy  h2
cache-control   no-cache, must-revalidate, max-age=0
content-encoding    gzip
content-type    application/json; charset=UTF-8
date    Mon, 29 Oct 2018 23:26:10 GMT
expires Wed, 11 Jan 1984 05:00:00 GMT
server  nginx
x-powered-by    PleskLin

RequestHeaders

Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate, br
Accept-Language nl,en-US;q=0.7,en;q=0.3
Connection  keep-alive
Host    secret
TE  Trailers
Upgrade-Insecure-Requests   1
User-Agent  Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0

Рабочие заголовки Json

Answerheaders

Accept-Ranges   bytes
Connection  Upgrade, Keep-Alive
Content-Encoding    gzip
Content-Length  4824
Content-Type    application/json
Date    Mon, 29 Oct 2018 23:23:23 GMT
ETag    "faf7-579664b90ce89-gzip"
Keep-Alive  timeout=2, max=100
Last-Modified   Mon, 29 Oct 2018 23:19:04 GMT
Server  Apache/2
Upgrade h2,h2c
Vary    Accept-Encoding,User-Agent

RequestHeaders

Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language nl,en-US;q=0.7,en;q=0.3
Connection  keep-alive
Host    secret
If-Modified-Since   Mon, 29 Oct 2018 23:19:04 GMT
If-None-Match   "faf7-579664b90ce89-gzip"
Upgrade-Insecure-Requests   1
User-Agent  Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0

MainActivity.java

   public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private TextView mTextView;
    private String mJSONURLString = "secret<3n";
    private RequestQueue requestQueree;
    private ArrayList<TheItem> StringList;

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

        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        mTextView = (TextView) findViewById(R.id.text_test);

        mTextView.setText("");

        // Initialize a new RequestQueue instance
        StringList = new ArrayList<>();
        requestQueree = Volley.newRequestQueue(mContext);

        Button btn1 = (Button) findViewById(R.id.button_1);
        btn1.setOnClickListener(btnListener);
        loadData();
        // Initialize a new JsonObjectRequest instance
    }

    private View.OnClickListener btnListener = new View.OnClickListener() {

        public void onClick(View v) {
            //do the same stuff or use switch/case and get each button ID and do different
            loadData();
            //stuff depending on the ID
        }

    };

    public void loadData() {
        StringList.clear();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, mJSONURLString, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // Do something with response
                        //mTextView.setText(response.toString());

                        // Process the JSON
                        try {
                            // Get the JSON array
                            JSONArray array = response.getJSONArray("posts");

                            // Loop through the array elements
                            for (int i = 0; i < array.length(); i++) {
                                // Get current json object
                                JSONObject student = array.getJSONObject(i);

                                // Get the current student (json object) data
                                String firstName = student.getString("title");

                                Log.e("Output", firstName);
                                // Display the formatted json data in text view
                                StringList.add(new TheItem(firstName));
                            }
                            TheItem currentitem = StringList.get(0);
                            String TheTitle = currentitem.getTitle();
                            mTextView.setText(TheTitle);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Do something when error occurred
                        String errorMessage = error.getClass().getSimpleName();
                        Log.e("error", errorMessage);
                    }
                });

        // Add JsonObjectRequest to the RequestQueue
        requestQueree.add(jsonObjectRequest);
    }
}

Ответы [ 2 ]

0 голосов
/ 31 октября 2018

Это был W3 Total Cache,

Плагин кэшировал файл json

0 голосов
/ 30 октября 2018

Сначала необходимо создать экземпляр RequestQueue следующим образом:

final TextView mTextView = (TextView) findViewById(R.id.text);
// ...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...