如何使用volley android发送原始文本数据

时间:2015-11-23 09:15:36

标签: android android-volley

工作原理: 使用volley的以下方法适用于发送JSON原始数据

我想做什么: 试图发送原始文本数据,但无法做到。如何实现这一点....下面的快照显示了我试图发送的邮递员数据

enter image description here

 public <T> void MasterWordListCall(Class<T> theClass, Activity context, int position,
                                       String mApi, int mGetOrPost, JSONObject stringObjectMap) {

        //progress = CommonFunctions.showLoadingDialog(progress, ActDrawAreaTwo.this);

        Map<String, String> params = new HashMap<>();
        Map<String, String> headers = new HashMap<String, String>();

        headers.put("Content-Type", "application/json");

        Iterator it = params.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry) it.next();
            Log.d(context.getClass().getCanonicalName(), "params - " + pairs.getKey() + ", " + pairs.getValue());
        }

        String url = AppConstants.SERVER_URL  + mApi + "/";

        Log.d("FinalUrl:->", url);

        RequestQueue requestQueue = Volley.newRequestQueue(ActLogin.this);
        CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST,
                url,
                stringObjectMap,
                params,
                headers,
                this.createRequestSuccessListener(),
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progress.dismiss();
                    }
                });
        RequestQueueHelper.addToRequestQueue(jsObjRequest, "");
        //requestQueue.add(jsObjRequest);

        //new JSONObject(params)
    }



    private Response.Listener<JSONObject> createRequestSuccessListener() {

        return new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                CommonFunctions.dismissLoadingDialog(progress);
                if(response!=null){

                    Toast.makeText(ActLogin.this,"Success",Toast.LENGTH_LONG);

                   /*Intent mIntent  = new Intent(ActLogin.this,ActSuccess.class);
                    mIntent.putExtra("data", mWord);
                    mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(mIntent);
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                    finish();*/

                }else if(response==null){

                }

            }
        };
    }

CustomRequest.java

public class CustomRequest extends JsonObjectRequest {

    private Listener<JSONObject> listener;
    private Map<String, String> params;
    private Map<String, String> headers;

    public CustomRequest(int put, String url,
                         JSONObject stringObjectMap, Map<String, String> params,
                         Map<String, String> headers,
                         Response.Listener<JSONObject> reponseListener,
                         ErrorListener errorListener) {
        //super(put, url, errorListener);

        super(put, url, (stringObjectMap == null) ? null : stringObjectMap.toString(), reponseListener,
                errorListener);
        this.listener = reponseListener;
        this.params = params;
        this.headers = headers;
    }

    /*public CustomRequest(int method,
                         String url,
                         Map<String, String> params,
                         Map<String, String> headers,
                         Listener<JSONObject> reponseListener,
                         ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
        this.headers = headers;
    }*/

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    protected Response<JSONObject> 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));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用排球String request

发送纯文本数据
   public void sendDataString(final VolleyCallback callback, final String appData) {
            String uri = String.format(Locale.US, URL);
            StringRequest stringRequest = new StringRequest(Request.Method.POST, uri,
                    new com.android.volley.Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.d(TAG, "String Success :" + response);
                        }
                    },
                    new com.android.volley.Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d(TAG, "String  Error In Request :" + error.toString());

                        }
                    }) {
                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                    String StringResponse = "";
                    try {
                        StringResponse = new String(response.data,
                                HttpHeaderParser.parseCharset(response.headers));
                        HttpHeaderParser.parseCharset(response.headers);
                        Log.d(TAG, "Response Headers " + response.headers);
                        Log.d(TAG, "String Status Code " + response.statusCode);
                        Log.d(TAG, "String response data :  " + new String(response.data));
                    } catch (UnsupportedEncodingException e) {
                        return Response.error(new ParseError(e));
                    }
                    callback.onSuccess(response.data.toString(), response.statusCode);
                    return super.parseNetworkResponse(response);
                }

                @Override
                public byte[] getBody() throws AuthFailureError {
                    return appData.getBytes();
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/text");
                    headers.put("charset", TYPE_UTF8_CHARSET);
                    return headers;
                }
            };
            stringRequest.setRetryPolicy(defaultRetryPolicy);
//if you are using OkHTTP with Stack.
            ApplicationController.getInstance().addToRequestQueue(stringRequest, TAG);
        }

其中appData是需要发送到服务器的原始数据。 callBack这不是强制性的,但如果你在其他一些类中调用该方法并等待响应,则需要HTTP Client,因为齐射是异步的。

在API 22之后def ventanaPrincipal(): top = Tkinter.Tk() var = Tkinter.StringVar() L1 = Tkinter.Label(top, text="Introduzca el nombre"+"\n"+ "completo del remitente:") E1 = Tkinter.Entry(top,textvariable = var) def buscar(): buscarPorNombreYApellidos(var.get()) B1 = Tkinter.Button(top, text ="Buscar", command = buscar) L1.pack(side = Tkinter.LEFT) B1.pack(side = Tkinter.RIGHT) E1.pack( side = Tkinter.RIGHT) top.mainloop() 被弃用,在Volley中使用;确保您有其他方法来解决此问题。