【问题标题】:Android volley post request not working properlyAndroid volley post 请求无法正常工作
【发布时间】:2016-11-11 09:48:21
【问题描述】:

我必须使用 volley 库向 url 发出 POST 请求。我为 volley 构建了以下自定义类:- CustomJSONObjectRequest

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONObject;

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

/**
 * Created by user on 4/14/2016.
 */

public class CustomJSONObjectRequest extends JsonObjectRequest {
    Map<String, String> mParams;

    public CustomJSONObjectRequest(int method, String url, JSONObject jsonRequest,
                                   Response.Listener<JSONObject> listener,
                                   Response.ErrorListener errorListener) {
        super(method, url, jsonRequest, listener, errorListener);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        return headers;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {

        return mParams;
    }

    @Override
    public RetryPolicy getRetryPolicy() {
        // here you can write a custom retry policy

        return super.getRetryPolicy();
    }


}

CustomVolleyRequestQueue

import android.content.Context;

import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;

/**
 * Created by Devastrix on 4/14/2016.
 */
public class CustomVolleyRequestQueue {

    private static CustomVolleyRequestQueue mInstance;
    private static Context mCtx;
    private RequestQueue mRequestQueue;

    private CustomVolleyRequestQueue(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();
    }

    public static synchronized CustomVolleyRequestQueue getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new CustomVolleyRequestQueue(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024);
            Network network = new BasicNetwork(new HurlStack());
            mRequestQueue = new RequestQueue(cache, network);
            // Don't forget to start the volley request queue
            mRequestQueue.start();
        }
        return mRequestQueue;
    }

}

我正在使用以下函数发出 POST 请求:-

RequestQueue mQueue = CustomVolleyRequestQueue.getInstance(context)
                .getRequestQueue();
        String url = "someURL";
       Log.d("URL= ", url);
        final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method.POST, url,
                new JSONObject(), new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {

                Log.d("post: ", response+"");

            }

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


            }
        }) {
            @Override
            protected Map<String, String> getParams() {

                Map<String,String> params = new HashMap<String, String>();
                params.put("A", "[[\"123\",\"456\",\"789\"]]"); // it is a json string actually
                params.put("B", "23-11-2016");
                params.put("C", "ABC");
                return params;
                //return query;
            }
        };
        jsonRequest.setTag(TAG);
        int socketTimeout = TIMEOUT;//30 seconds - 
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        jsonRequest.setRetryPolicy(policy);
        mQueue.add(jsonRequest);

但问题是请求返回空数据,而当我使用某些第三方应用程序进行 POST 请求时,它返回正确的结果。可能的错误是什么?

EDIT - 实际上响应不为空。真实的反应是这样的。

{
  "data" : ""
}

但是数据键不应该有空值。所以我认为参数有问题或者参数没有正确发送。但是我检查过的参数是完全正确的。

【问题讨论】:

  • 您希望服务器返回什么数据以响应成功的 (2xx) POST?另外,该数据应该采用什么格式? JSON?
  • 数据为 JSON 格式。键“数据”应包含一些 JSONObject,但响应显示“数据”键具有空键。
  • 我明白了。我唯一能想到的是服务器确实没有为data 属性返回任何内容。尝试在服务器端添加日志记录,这样您就可以在构建响应时准确地看到服务器正在打包到 data 中的内容。或者,在应用程序端,在其中的数据转换为JSONObject 之前拦截原始响应,并检查其内容。您应该能够通过覆盖 protected Response&lt;JSONObject&gt; parseNetworkResponse(NetworkResponse response) { 并使用调试器或日志记录来做到这一点。
  • 我也面临同样的问题,凌空返回我空字符串“”,不知道为什么。 :(

标签: android json post android-volley


【解决方案1】:

请将此依赖项添加到您项目的 build.gradle 方法中。 在此之后添加您要发送到服务器的参数。

compile 'com.android.volley:volley:1.0.0'

现在将此活动添加到您的项目中。

public class MainActivity extends AppCompatActivity {
    private  ProgressDialog progress_dialog;
    private RequestQueue queue;
    private HashMap<String, String> map = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        queue= Volley.newRequestQueue(getApplicationContext());
        GetEventCodeResponse("d@gmail.com","4");

    }
    public void GetEventCodeResponse(String email,String event){
        progress_dialog = new ProgressDialog(this);
        progress_dialog.setMessage("Getting data, please wait a moment...");
        progress_dialog.show();
        map.put("username", email);
        map.put("eventcode", event);
        getResponseFromServer("your own url",map);
    }
    public void getResponseFromServer(String url, final HashMap<String, String> map) {
        System.out.println("url----"+url);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("response reviw--",response);
                        progress_dialog.dismiss();
                       /* rating();*/
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        try{
                            Log.e("sign error password", new String(error.networkResponse.data));

                        }catch (Exception e){
                            Toast.makeText(MainActivity.this, "try again", Toast.LENGTH_SHORT).show();
                        }

                        progress_dialog.dismiss();
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() {
                return map;
            }
        };
        queue.add(stringRequest);
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                100000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }
}

【讨论】:

  • 不工作...这个代码其实和我的很相似
【解决方案2】:

只是为了确认一下,请求肯定是成功的,并且正在调用您提供给请求的 Response.Listener&lt;JSONObject&gt; 实例的 onResponse(JSONObject response) 方法,响应为 null?

另外,是否有 Volley 相关的出现在 logcat 中?

响应 cmets 的更新

我的感觉是,我们仍未确定您所看到问题的明确根本原因,因此我无法保证以下代码能够解决该问题。不过,如您所问,请尝试以下操作:

RequestQueue mQueue = CustomVolleyRequestQueue.getInstance(context).getRequestQueue();
String url = "someURL";
Log.d("URL= ", url);

final JSONObject requestBody;
try {
    requestBody = new JSONObject();
    requestBody.put("A", new JSONArray(new String[]{ "123", "456", "789" });
    requestBody.put("B", "23-11-2016");
    requestBody.put("C", "ABC");
} catch (JSONException exception) {
    // error handling which, at least in theory, shouldn't be needed ...
}

final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method.POST, url,
            requestBody, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {

            Log.d("post: ", response+"");

        }

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


        }
    });

jsonRequest.setTag(TAG);
int socketTimeout = TIMEOUT;//30 seconds - 
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonRequest.setRetryPolicy(policy);
mQueue.add(jsonRequest);

【讨论】:

  • 是的响应已生成,但它为空。不,我没有使用 Volley logcat
  • 这很奇怪......JsonObjectRequest 在成功时创建一个新的JSONObject,如果它无法解析响应正文数据,则会引发异常,所以我本来期望response通过onResponse 方法提供的对象永远不会是null?抱歉,我没能帮上忙……我会继续考虑的!
  • 其实响应不是空的。真正的响应是一个键值对,其中的值作为空字符串返回。所以我认为参数有问题,或者参数没有正确发送。但是我检查过的参数是完全正确的。
  • 您可以访问服务器吗?如果是这样,您可以检查日志,也许还有由于 POST 存储的数据(如果有)。此外,如果您在请求正文中发布 JSON 对象,则通过请求构造函数的 JSONObject jsonRequest 参数提供数据可能更容易。这将为您处理编码等等,这是一件少担心的事情(例如,与发送 JSON 数组的字符串表示相比)。
  • 好的。你能把它写成你所说的JSON参数的代码吗?
猜你喜欢
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 2023-01-12
  • 2018-02-11
相关资源
最近更新 更多