【问题标题】:Android volley put request not working with name value pairsAndroid volley put 请求不适用于名称值对
【发布时间】:2015-06-22 11:07:14
【问题描述】:

在我的应用程序中,我需要使用 HttpPut 方法将一些参数发布到服务器。所以为此我检查了基本身份验证技术并成功地以这种方式获得相同的结果。但是当我尝试用 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 http-headers android-volley basic-authentication put


    【解决方案1】:

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

    你有两个选择

    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

    【讨论】:

    • 谢谢!!让我试试@Zain :)
    【解决方案2】:

    经过几次尝试后,我终于找到了问题的解决方案,我也得到了与 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 );
            }
        }
    
    }
    

    干杯!!!

    【讨论】:

      猜你喜欢
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      相关资源
      最近更新 更多