Android volley put 请求不适用于名称值对

Android volley put request not working with name value pairs

在我的应用程序中,我需要使用 HttpPut 方法 post 向服务器发送一些参数。所以为此我检查了基本身份验证技术并成功地以这种方式获得了相同的结果。但是,当我尝试使用 Json Volley 实现相同功能时,我无法获得结果。每次它抛出服务器错误。

这是我使用 Asynctask::

通过基本身份验证的代码
@Override
        protected Void doInBackground( String... params )
        {
            // TODO Auto-generated method stub

            try
            {
                HttpPut request = new HttpPut( params[0] );

                Log.d("debug", "Posting URL" + params[0]);

                String creds = String.format( "%s:%s",
                        "user123",
                        "abcd" );

                String auth = "Basic " + Base64.encodeToString( creds.getBytes(),
                        Base64.NO_WRAP );

                request.setHeader( "Authorization",
                        auth );

                List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
                urlParameters.add(new BasicNameValuePair("id", "409"));
                urlParameters.add(new BasicNameValuePair("parent_id", "0"));
                urlParameters.add(new BasicNameValuePair("content", "I am android developer"));
                urlParameters.add(new BasicNameValuePair("email", "email@example.com"));
                urlParameters.add(new BasicNameValuePair("username", "King Of Masses"));

                request.setEntity(new UrlEncodedFormEntity(urlParameters));

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpResponse response = httpClient.execute( request );
                HttpEntity Entity = response.getEntity();
                String jsondata = EntityUtils.toString( Entity );

                Log.d( "debug",
                        "Response Code::  " + response.getStatusLine().getStatusCode() );

                Log.d( "debug",
                        "Json Data in Asynctask:: " + jsondata );

                JSONObject ljsJsonObject=new JSONObject(jsondata);

                Log.d( "debug",
                        "Json Object Data:: " + ljsJsonObject.toString() );

            }
            catch( ClientProtocolException e )
            {
                Log.d( "debug",
                        "Exception" + e.toString() );
                e.printStackTrace();
            }
            catch( IOException e )
            {

                Log.d( "debug",
                        "Exception" + e.toString() );
                e.printStackTrace();
            }
            catch( Exception e )
            {

                e.printStackTrace();
            }
            return null;
        } 

所以在上面的方法中我得到了我预期的结果..但是我无法用 VolleyJson 实现相同的结果..任何人都可以指导我如何实现这一点..我也试过了很多方法,比如(getBody(),getParams())但不幸的是对我没有任何作用..

任何帮助将不胜感激.. 谢谢

Android Volley 中存在一个错误,它无法读取 getParas 键值对。

你有2个选项

  1. 使用 StringRequest 然后将其解析为 JSON(我使用这个!)- 像这样 - 然后像往常一样覆盖 getParams 方法。

    RequestQueue queue = Volley.newRequestQueue(this);
    String url ="http://www.google.com";
    
    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        JSONObject obj = new JSONObject(response);
        //Now you can manipulate/store your JSON
    
    }
        }, new Response.ErrorListener() {
      @Override
         public void onErrorResponse(VolleyError error) {
           mTextView.setText("That didn't work!");
        }
      })
     {  
    
     protected Map<string, string=""> getParams() throws      com.android.volley.AuthFailureError {  
        Map<string, string=""> params = new HashMap<string, string="">();  
        params.put("param1", num1);  
        params.put("param2", num2);  
        return params;  
        };  
    };  
               // Add the request to the RequestQueue.
               queue.add(stringRequest);
    
  2. 使用自定义请求对象 - 类似于这样的东西

    CustomRequest request = new CustomRequest(Method.POST, URL, null, new Response.Listener<JSONObject>() {
        @Override
       public void onResponse(JSONObject response) {
           Toast.makeText(getActivity(), response.toString(),  Toast.LENGTH_SHORT).show();
         }
     }, new Response.ErrorListener() {
         @Override
        public void onErrorResponse(VolleyError error) {
           Toast.makeText(getActivity(), "Error.", Toast.LENGTH_SHORT).show();
       }
       }) {
         @Override
         protected Map<String, String> getParams() throws AuthFailureError {
          Map<String, String> params = new HashMap<String, String>();
           params.put("id", id);
           params.put("password", password);
           return params;
        }
       };
     VolleySingleton.getInstance().addToRequestQueue(request);
    

CustomRequest 助手的代码已发布here

经过几次尝试,我终于找到了我的问题的解决方案,我也用 VollyJson 得到了相同的结果。我在这里发布了解决方案。可能对以后的某个人有帮助。

这是我的 VollyJson 调用::

String postUrl="http://xxxxxxxxx/xxxx";

final List<NameValuePair> params = new ArrayList<NameValuePair>();


                params.add(new BasicNameValuePair("id", "409"));
                params.add(new BasicNameValuePair("parent_id", "0"));
                params.add(new BasicNameValuePair("content", "I am android developer"));
                params.add(new BasicNameValuePair("email", "email@example.com"));
                params.add(new BasicNameValuePair("username", "King Of Masses"));


        StringRequest stringReq = new StringRequest( Method.PUT,
                                                     postUrl,
                                                     new Response.Listener<String>()
                                                     {

                                                         @Override
                                                         public void onResponse( String arg0 )
                                                         {

                                                             // TODO Auto-generated method stub

                                                             mListener.notifyResponse( arg0 );

                                                         }
                                                     },
                                                     new Response.ErrorListener()
                                                     {

                                                         @Override
                                                         public void onErrorResponse( VolleyError arg0 )
                                                         {
                                                             // TODO Auto-generated method stub

                                                             trimErrorMessage( arg0,
                                                                               mListener );

                                                         }
                                                     } )
        {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError
            {
                // TODO Auto-generated method stub
                HashMap<String, String> params1 = new HashMap<String, String>();
                String cred = String.format( "%s:%s",
                                              "user123",
                                               "abcd" );
                String auth = "Basic " + Base64.encodeToString( cred.getBytes(),
                                                                Base64.NO_WRAP );

                /*params1.put( "Content-Type",
                             "application/json; charset=utf-8" );*/
                params1.put( "Authorization",
                             auth );

                return params1;
            }

            @Override
            protected Map<String, String> getParams() throws AuthFailureError
            {
                // TODO Auto-generated method stub
                Map<String, String> nParams = new HashMap<String, String>();
                for( int i = 0; i < params.size(); i++ )
                {
                    nParams.put( params.get( i ).getName(),
                                 params.get( i ).getValue() );
                }
                return nParams;
            }
        };
        int socketTime = 30000;
        RetryPolicy policy = new DefaultRetryPolicy( socketTime,
                                                     DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                                                     DefaultRetryPolicy.DEFAULT_BACKOFF_MULT );

        stringReq.setRetryPolicy( policy );
        AppController.getInstance().adToRequestQure( stringReq );

这是我的 AppController

public class AppController extends Application
{

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private DisplayImageOptions options;
    LruBitmapCache mLruBitmapCache;
    MixpanelAPI mixPanel;
    public static GoogleAnalytics analytics;
    public static Tracker tracker;

    private static AppController mInstance;

    @Override
    public void onCreate()
    {
        // TODO Auto-generated method stub
        super.onCreate();
        mInstance = this;

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( getApplicationContext() ).imageDownloader( new BaseImageDownloader( getApplicationContext(),
                                                                                                                                                    5 * 1000,
                                                                                                                                                    20 * 1000 ) )
                .build();

        options = new DisplayImageOptions.Builder().showImageOnFail( R.drawable.no_image )
                .showImageOnLoading( R.drawable.no_image )
                .imageScaleType( ImageScaleType.EXACTLY )
                .bitmapConfig( Bitmap.Config.RGB_565 )
                .build();

        ImageLoader.getInstance().init( config );

        YandexMetrica.initialize(getApplicationContext(), AnalyticsUtills.KAPITAL_APP_API_KEY_YANDIX);


    }

    public static synchronized AppController getInstance()
    {
        return mInstance;
    }

    public RequestQueue getRequestQueue()
    {
        if( mRequestQueue == null )
        {
            mRequestQueue = Volley.newRequestQueue( getApplicationContext() );
        }
        return mRequestQueue;

    }

    public MixpanelAPI getMixpanelRef()
    {

        return MixpanelAPI.getInstance(getApplicationContext(), AnalyticsUtills.KAPITAL_APP_API_KEY_MIXPANEL);

    }

    public Tracker getGoogleTrackerRef()
    {
        analytics =  GoogleAnalytics.getInstance(getApplicationContext());
        tracker =  analytics.newTracker(AnalyticsUtills.KAPITAL_APP_API_KEY_GOOGLE);
        return tracker;
    }

    public ImageLoader getImageLoader()
    {
        if( mImageLoader == null )
        {

            mImageLoader = ImageLoader.getInstance();
        }

        return mImageLoader;

    }

    public DisplayImageOptions getDisplayImageOptions()
    {

        if( options == null )
        {
            options = new DisplayImageOptions.Builder().showImageOnFail( R.drawable.no_image )
                    .showImageOnLoading( R.drawable.no_image )
                    .imageScaleType( ImageScaleType.EXACTLY )
                    .displayer( new FadeInBitmapDisplayer( 300 ) )
                    .bitmapConfig( Bitmap.Config.RGB_565 )
                    .build();
        }

        return options;
    }

    public LruBitmapCache getLruBitmapCache()
    {
        if( mLruBitmapCache == null )
            mLruBitmapCache = new LruBitmapCache();
        return this.mLruBitmapCache;

    }

    public <T> void addToRequestQueue( Request<T> req,
            String tag )
    {
        Log.d( "debug",
               "TAG is not ther" );
        Log.d( "debug",
               "Quew nu" + getRequestQueue().getSequenceNumber() );
        req.setTag( TextUtils.isEmpty( tag ) ? TAG
            : tag );
        getRequestQueue().add( req );

    }

    public <T> void adToRequestQure( Request<T> req )
    {
        req.setTag( TAG );
        getRequestQueue().add( req );
    }

    public void cancelPendingRequests( Object tag )
    {
        if( mRequestQueue != null )
        {
            mRequestQueue.cancelAll( tag );
        }
    }

}

干杯!!!