2014-10-02 7 views
11

इन उदाहरणों में से किसी का उपयोग करना: http://developer.android.com/training/volley/request.htmlवॉली में त्रुटि प्रतिक्रिया की सामग्री तक कैसे पहुंचे?

मैं समझता हूँ कि कैसे एक सफल अनुरोध की प्रतिक्रिया पर कार्रवाई करने के लिए, और कैसे पता लगाने और एक त्रुटि के लिए प्रतिक्रिया करने के लिए।

हालांकि, सर्वर से 40x या 50x प्रतिक्रिया में एक त्रुटि हो सकती है, जिस स्थिति में प्रतिक्रिया में अभी भी डेटा (हेडर और बॉडी) हो सकता है।

लेकिन त्रुटि श्रोता केवल वॉलीएरर ऑब्जेक्ट को पारित कर दिया गया है (जो अपवाद का उप-वर्ग है यदि मुझे गलत नहीं है) और प्रतिक्रिया ऑब्जेक्ट नहीं है।

मैं त्रुटि प्रतिक्रिया की सामग्री तक कैसे पहुंचूं?

उत्तर

4

StringRequest में उदाहरण के लिए:

@Override 
protected Response<String> parseNetworkResponse(NetworkResponse response) { 
    Map<String, String> responseHeaders = response.headers; 
    if response.statusCode == 401) { 
     // Here we are, we got a 401 response and we want to do something with some header field; in this example we return the "Content-Length" field of the header as a succesfully response to the Response.Listener<String> 
     Response<String> result = Response.success(responseHeaders.get("Content-Length"), HttpHeaderParser.parseCacheHeaders(response)); 
     return result; 
    } 
    return super.parseNetworkResponse(response); 
} 
+0

एक '(' अगर कथन में अनुपलब्ध है, तो आपके उत्तर के लिए धन्यवाद :) –

23

VolleyError वस्तु एक networkResponse संदर्भ है, जो अपने आप में एक 'डेटा' सदस्य है, जो प्रतिक्रिया शरीर के एक बाइट सरणी है है है। यदि आप प्रतिक्रिया में त्रुटि कोड के मामले में डेटा देखना चाहते हैं, तो आप इस तरह कुछ उपयोग कर सकते हैं:

@Override 
public void onErrorResponse(VolleyError error) { 
    String body; 
    //get status code here 
    String statusCode = String.valueOf(error.networkResponse.statusCode); 
    //get response body and parse with appropriate encoding 
    if(error.networkResponse.data!=null) { 
     try { 
      body = new String(error.networkResponse.data,"UTF-8"); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 
    } 
    //do stuff with the body... 
} 
संबंधित मुद्दे