Как добавить заголовок и тело в REST-запрос, используя Volley? - PullRequest
0 голосов
/ 05 марта 2019

Ранее я сделал запрос к https://www.thecocktaildb.com/api/json/v1/1/search.php?i=beer, который является публичным API, который не нуждается в заголовке и теле, но теперь мне нужно отправить запрос (POST) на https://api.candy.mn/resource/partner/v1/sell, который требуетАвторизация и Content-Type в заголовке и некоторые параметры в теле.Я не знаю, как добавить их в мой код:

package com.example.john.candyapi;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    private TextView mTextViewResult;

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

    mTextViewResult = findViewById(R.id.text_view_result);

    String URL = "https://www.thecocktaildb.com/api/json/v1/1/search.php?i=beer";
    String in = "ingridients";

    //creating requestQueue object by calling newRequestQueue on Volley class
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //creating json obeject request
    JsonObjectRequest objectRequest = new JsonObjectRequest(
            Request.Method.POST,
            URL,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                //if response is successful
                public void onResponse(JSONObject response) {
                        try{
                            //get from strDescription of 0th row of ingridients
                            JSONArray jsonarray = response.getJSONArray("ingredients");
                            JSONObject one = jsonarray.getJSONObject(0);
                            String strDescr = one.getString("strDescription");
                            //append this String to TextView
                            mTextViewResult.append(strDescr);
                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                        Log.e("Rest Response", error.toString());
                }
            }
    );

    //requesting created request
    requestQueue.add(objectRequest);
}


}

1 Ответ

0 голосов
/ 05 марта 2019
   JSONObject parms = new JSONObject()
   parms.put("parm1", "value")


  //creating json obeject request
    JsonObjectRequest objectRequest = new JsonObjectRequest(
            Request.Method.POST,
            URL,
            parms,
            new Response.Listener<JSONObject>() {
                @Override
                //if response is successful
                public void onResponse(JSONObject response) {
                        ......
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                        Log.e("Rest Response", error.toString());
                }
            }
    ) {     
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError { 
                Map<String, String>  params = new HashMap<String, String>();  
                params.put("Content-Type", "application/json");  

                return params;  
        }
    };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...