0

在我的應用程序中,我需要使用HttpPut方法向服務器發佈一些參數。所以爲此,我使用基本身份驗證技術進行了檢查,並以這種方式獲得相同的結果。但是當我試圖用Json Volley實現時,我無法得到結果。每次它拋出服務器錯誤。Android排除請求不與名稱值對一起工作

這裏是

@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; 
     } 

所以在這上面的方式,我得到的結果我的預期..但我無法實現與VolleyJson同我的代碼通過使用的AsyncTask基本身份驗證:: ..任何一個可以指導我如何做到這一點。我嘗試了太多的方法一樣(getBody(),getParams()方法),但遺憾的是沒有工作對我來說..

任何幫助將是非常感激。謝謝

回答

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 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); 

這裏是我的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); 
     } 
    } 

} 

乾杯!

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); 
    

爲CustomRequest助手的代碼發佈here

+1

謝謝!讓我試試@Zain :) –