如何使用Volley将对象发布到JSON数组中

时间:2020-08-19 11:30:17

标签: android json post android-volley

这是我的json文件:

https://api.jsonbin.io/b/5f3ac924b88c04101cf5d78f

如您所见,我有一个名为employees的数组,其中包含描述为firstname, age, mail的员工。

我想发布一个新员工,例如

{"name": "Alberto", "age": 46, "mail": "alberto@example.com"}

使用Volley库进入该json文件。

这就是我所拥有的

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text_view_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimary"
        android:textSize="20sp" />

    <Button
        android:id="@+id/button_parse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Parse"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.976" />

    <Button
        android:id="@+id/button_post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Post random data"
        app:layout_constraintBottom_toTopOf="@+id/button_parse"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.859" />

</androidx.constraintlayout.widget.ConstraintLayout> 

MainActivity.java

package com.example.volleydemo;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
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.HttpHeaderParser;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView textViewResults;
    private Button buttonParse;
    private Button buttonPostRandomData;
    private RequestQueue requestQueue;

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

        initializeViewComponents();

        initializeVolleyRequestQueue();

        initializeListenersOnViewComponents();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_parse:
                // jsonParse();
                break;
            case R.id.button_post:
                jsonPostRequest();
                break;
        }
    }

    public void initializeViewComponents() {
        textViewResults = findViewById(R.id.text_view_result);
        buttonParse = findViewById(R.id.button_parse);
        buttonPostRandomData = findViewById(R.id.button_post);
    }

    public void initializeVolleyRequestQueue() {
        requestQueue = Volley.newRequestQueue(this);
    }

    public void initializeListenersOnViewComponents() {
        buttonParse.setOnClickListener(this);
        buttonPostRandomData.setOnClickListener(this);
    }

    public void jsonPostRequest() {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        final String URL = "https://api.jsonbin.io/b/5f3ac924b88c04101cf5d78f";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("VOLLEY", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("VOLLEY", error.toString());
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("firstname", "Alberto");
                params.put("age", String.valueOf(46));
                params.put("mail", "alberto@example.com");
                return params;
            }

            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type","application/x-www-form-urlencoded");
                return headers;
            }

            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String responseString = "";
                if (response != null) {
                    responseString = String.valueOf(response.statusCode);
                    // can get more details such as response.headers
                }
                assert response != null;
                return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        requestQueue.add(stringRequest);
    }
}

当我点击Post random data按钮时,我得到:

E / Volley:[1558] BasicNetwork.performRequest:https://api.jsonbin.io/b/5f3ac924b88c04101cf5d78f的意外响应代码404

  • 我该如何解决?

0 个答案:

没有答案