19

Volley を使用して API とやり取りしています。JSON 配列を返すサービスにポスト リクエスト (パラメーター付き) を送信する必要があります。

JsonObjectRequest には、メソッドと一連のパラメーターを受け取るコンストラクターがあります。

JsonObjectRequest(int method, java.lang.String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) 

ただし、JSONArrayRequest (必要なもの) には、フォームのコンストラクターが 1 つしかありません。

JsonArrayRequest(java.lang.String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) 

データを含む POST リクエストを送信するにはどうすればよいですか?

4

9 に答える 9

7

私は怠け者で、Volley ライブラリを自分でビルドしませんでした (.jar を使用しただけです)。そのため、ソース コードがありませんJSONArrayRequest

            // NO CONSTRUCTOR AVAILABLE FOR POST AND PARAMS FOR JSONARRAY!
            // overridden the necessary functions for this
            @Override
            public byte[] getBody() {
                try {
                    return paramsArray.toString().getBytes("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            public int getMethod() {
                return Method.POST;
            }
于 2014-08-01T14:22:16.707 に答える
2

このコードはあなたが望むものを作ります

    Volley.newRequestQueue(context).add(
            new JsonRequest<JSONArray>(Request.Method.POST, "url/", null,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {

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

                        }
                    }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("param1", "one");
                    params.put("param2", "two");
                    return params;
                }

                @Override
                protected Response<JSONArray> parseNetworkResponse(
                        NetworkResponse response) {
                    try {
                        String jsonString = new String(response.data,
                                HttpHeaderParser
                                        .parseCharset(response.headers));
                        return Response.success(new JSONArray(jsonString),
                                HttpHeaderParser
                                        .parseCacheHeaders(response));
                    } catch (UnsupportedEncodingException e) {
                        return Response.error(new ParseError(e));
                    } catch (JSONException je) {
                        return Response.error(new ParseError(je));
                    }
                }
            });
于 2015-02-21T17:11:25.230 に答える
2

パラメータ リクエストを送信し、JSONarray リクエストを使用してパラメータに従ってカスタム レスポンスを返す最も簡単な方法は、URL 自体に get パラメータ値を追加することです。

String URL ="http://mentormentee.gear.host/android_api/Message.aspx?key="+keyvalue;

wherekeyvalueパラメータ値を指定し、この URL を JsonArrayRequest URL シンプルに追加します。

    JsonArrayRequest searchMsg= new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {

        @Override
        public void onResponse(JSONArray response) {
            Log.d(TAG, response.toString());


            // Parsing json
            for (int i = 0; i < response.length(); i++) {
                try {

                    JSONObject obj = response.getJSONObject(i);
                    Message msg = new Message();
                    msg.setMessageThread(obj.getString("msgThread"));
                    msg.setUserName(obj.getString("Username"));
                    msg.setDate(obj.getString("msgDate"));

                    // adding movie to movies array
                    MessageList.add(msg);

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

            }

            // notifying list adapter about data changes
            // so that it renders the list view with updated data
            adapter.notifyDataSetChanged();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
           // hidePDialog();

        }
    });
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(searchMsg);
}
于 2015-05-12T13:38:48.613 に答える
1
You can use this 

package HelperClass;
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;

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

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * A request for retrieving a {@link JSONArray} response body at a given URL.enter code here
 */
public class MyjsonPostRequest extends JsonRequest<JSONArray> {

    protected static final String PROTOCOL_CHARSET = "utf-8";



    /**
     * Creates a new request.
     * @param method the HTTP method to use
     * @param url URL to fetch the JSON from
     * @param requestBody A {@link String} to post with the request. Null is allowed and
     *   indicates no parameters will be posted along with request.
     * @param listener Listener to receive the JSON response
     * @param errorListener Error listener, or null to ignore errors.
     */
    public MyjsonPostRequest(int method, String url, String requestBody,
                            Listener<JSONArray> listener, ErrorListener errorListener) {
        super(method, url, requestBody, listener,
                errorListener);
    }

    /**
     * Creates a new request.
     * @param url URL to fetch the JSON from
     * @param listener Listener to receive the JSON response
     * @param errorListener Error listener, or null to ignore errors.
     */
    public MyjsonPostRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
        super(Method.GET, url, null, listener, errorListener);
    }

    /**
     * Creates a new request.
     * @param method the HTTP method to use
     * @param url URL to fetch the JSON from
     * @param listener Listener to receive the JSON response
     * @param errorListener Error listener, or null to ignore errors.
     */
    public MyjsonPostRequest(int method, String url, Listener<JSONArray> listener, ErrorListener errorListener) {
        super(method, url, null, listener, errorListener);
    }

    /**
     * Creates a new request.
     * @param method the HTTP method to use
     * @param url URL to fetch the JSON from
     * @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and
     *   indicates no parameters will be posted along with request.
     * @param listener Listener to receive the JSON response
     * @param errorListener Error listener, or null to ignore errors.
     */
    public MyjsonPostRequest(int method, String url, JSONArray jsonRequest,
                            Listener<JSONArray> listener, ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
    }

    /**
     * Creates a new request.
     * @param method the HTTP method to use
     * @param url URL to fetch the JSON from
     * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
     *   indicates no parameters will be posted along with request.
     * @param listener Listener to receive the JSON response
     * @param errorListener Error listener, or null to ignore errors.
     */
    public MyjsonPostRequest(int method, String url, JSONObject jsonRequest,
                            Listener<JSONArray> listener, ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
    }

    /**
     * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is
     * <code>null</code>, <code>POST</code> otherwise.
     *
     * @see #MyjsonPostRequest(int, String, JSONArray, Listener, ErrorListener)
     */
    public MyjsonPostRequest(String url, JSONArray jsonRequest, Listener<JSONArray> listener,
                            ErrorListener errorListener) {
        this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
                listener, errorListener);
    }

    /**
     * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is
     * <code>null</code>, <code>POST</code> otherwise.
     *
     * @see #MyjsonPostRequest(int, String, JSONObject, Listener, ErrorListener)
     */
    public MyjsonPostRequest(String url, JSONObject jsonRequest, Listener<JSONArray> listener,
                            ErrorListener errorListener) {
        this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
                listener, errorListener);
    }

    @Override
    protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONArray(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

}
于 2015-05-19T20:29:35.183 に答える
1

あなたの問題は解決したかもしれませんが、これが他のユーザーに役立つことを願っています. 私がしたことは、それを拡張して新しいカスタムクラスを作成したことです..ここにコードがあります。

public class CustomJsonRequest extends Request {

Map<String, String> params;       
private Response.Listener listener; 

public CustomJsonRequest(int requestMethod, String url, Map<String, String> params,
                      Response.Listener responseListener, Response.ErrorListener errorListener) {

    super(requestMethod, url, errorListener);
    this.params = params;
    this.listener = responseListener;
}

@Override
protected void deliverResponse(Object response) {
    listener.onResponse(response); 

}

@Override
public Map<String, String> getParams() throws AuthFailureError {
         return params;
}

@Override
protected Response parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        return Response.success(new JSONObject(jsonString),
        HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

}

JsonArrayRequest または JsonObjectRequest の代わりにこのクラスを使用できます。また、これにより、php が $_POST の post パラメータをキャッチできないという問題も解決されます。

于 2014-01-21T18:41:12.200 に答える
0
List<Map<String,String>> listMap =  new ArrayList<Map<String, String>>();
        Map<String,String> map  = new HashMap<String,String>();
        try {

            map.put("email", customer.getEmail());
            map.put("password",customer.getPassword());

        } catch (Exception e) {
            e.printStackTrace();
        }
        listMap.add(map);

        String url = PersonalConstants.BASE_URL+"/url";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.POST, url, String.valueOf(new JSONArray(listMap)),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.d(App.TAG, jsonObject.toString());
                    }
                }, new Response.ErrorListener (){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d(App.TAG,volleyError.toString());
            }
        }
        );
        App.getInstance().getmRequestQueue().add(jsonObjectRequest);
于 2015-04-30T15:06:08.120 に答える