Android排球请求不使用名称值对

时间:2015-06-22 11:07:15

标签: android http-headers android-volley basic-authentication put

在我的应用程序中,我需要使用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()),但不幸的是没有任何对我有用..

任何帮助都将非常感谢..谢谢

2 个答案:

答案 0 :(得分:1)

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);
    
  3. CustomRequest帮助程序的代码已发布here

答案 1 :(得分:0)

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

}

干杯!!!