Android凌空帖请求无法正常工作

时间:2016-11-11 09:48:22

标签: android json post android-volley

我必须使用排球库向网址发出POST请求。我为排球建立了以下自定义类: - 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请求时,它返回正确的结果。什么可能是错误?

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

{
  "data" : ""
}

但数据键不应该有空值。我认为params存在问题或params没有正确发送。但这些参数完全正确我已经检查过了。

2 个答案:

答案 0 :(得分:0)

请将此依赖项添加到项目的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));
    }
}

答案 1 :(得分:0)

要确认,请求肯定会成功,并且正在调用您为请求提供的onResponse(JSONObject response)实例的Response.Listener<JSONObject>方法,响应为null

此外,是否有与Volley相关的内容出现在logcat中?

更新以回应评论

我的感觉是,我们仍然没有找到您所看到的问题的明确根本原因,因此我无法保证以下代码将解决它。但是,正如您所问,请尝试以下方法:

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);