Search code examples
androidhttp-headersandroid-volleybasic-authenticationput

Android volley put request not working with name value pairs


In my application i need to post some parameters to the server by using HttpPut method. so for that i checked with the Basic Authentication technique and succeed to get the same in that way. But when i tried to implement the same with Json Volley i am unable to get the result. Every time it is throwing the server error.

Here is my code to pass the Basic Authentication using 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 protected]"));
                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;
        } 

So in this above way i got the result what i expected.. but i am unable to implement the same with VolleyJson.. Can any one guide me how to achieve this.. I tried too many ways like ( getBody(), getParams()) but unfortunately nothing worked for me..

Any help would be highly appreciate.. Thank you


Solution

  • After few trails i finally got the solution for my question and i got the same result with VollyJson too.. Here i am posting the solution. It may be helpful for some one in future.

    Here is my VollyJson call::

    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 protected]"));
                    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 );
    

    Here is my 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 );
            }
        }
    
    }
    

    Cheers !!!