Creating GET and POST request in android; API response handling

Android में दो everyday API calls: एक GET request endpoint से data fetch करता है, एक POST request इसे data भेजता है, और दोनों में आप response, और किसी भी error को, Volley के callbacks में handle करते हैं।

11 min read · 8 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Fetch और Send, दो Calls जो आपको चाहिए

अब सब कुछ साथ आता है। FestConnect Mobile events list fetch करता है (एक GET) और एक नई registration भेजता है (एक POST), दोनों एक REST API को, Volley इस्तेमाल करते हुए, JSON parse करते हुए, और response handle करते हुए। यह final lesson REST, JSON, और Volley को उन दो requests में wire करता है जो आप सबसे ज़्यादा करेंगे।

GET पढ़ता है; POST लिखता है। दोनों में, Volley call को UI thread से हटकर run करता है और result एक callback में हाथ में देता है, जहाँ आप या तो data इस्तेमाल करते हैं या error handle करते हैं। इन दो को master कीजिए, और आप Android से लगभग किसी भी web API को consume कर सकते हैं।

Theory

एक GET Request: Events Fetch करना

एक GET data retrieve करता है। आप Request.Method.GET, endpoint URL, और (GET के लिए) एक null body, plus आपके success और error listeners से एक Volley request create करते हैं।

जब यह succeed होता है, response आता है, एक JsonObjectRequest के लिए पहले से parsed, एक JSONObject (या JSONArray) की तरह, जिसे आप फिर आपने जो parsing सीखी है वह इस्तेमाल करते हुए पढ़ते हैं: events array निकालिए, इसे loop कीजिए, हर name और seats extract कीजिए, और UI update कीजिए। तो एक GET है: endpoint को भेजिए, JSON receive कीजिए, इसे parse कीजिए, इसे display कीजिए। यही तरीका है app एक remote server से एक live list दिखाती है।

Practical

Events को GET कीजिए, Response Handle कीजिए

val getEvents = JsonObjectRequest(
    Request.Method.GET, "https://api.example.com/events", null,
    { response ->                       // success
        val arr = response.getJSONArray("events")
        for (i in 0 until arr.length()) {
            val e = arr.getJSONObject(i)
            addToList(e.getString("name"), e.getInt("seats"))
        }
    },
    { error -> showError("Could not load events") }   // error handling
)
queue.add(getEvents)

Practical

एक POST Request: एक Registration भेजना

// Build the JSON body to send
val body = JSONObject().apply {
    put("studentName", "Riya")
    put("eventId", 5)
}

val postReg = JsonObjectRequest(
    Request.Method.POST, "https://api.example.com/registrations", body,
    { response -> showMessage("Registered!") },        // success
    { error -> showError("Registration failed") }      // error handling
)
queue.add(postReg)   // POST sends 'body' to the server, which processes it

Formula

हमेशा Success और Error दोनों Handle कीजिए

हर request के दो possible outcomes होते हैं, और आप दोनों handle करते हैं। Success listener response receive करता है: data इस्तेमाल या parse कीजिए और UI update कीजिए। Error listener एक VolleyError receive करता है: user को एक clear message दिखाइए, और (अगर useful हो) एक status code या network cause के लिए error inspect कीजिए।

कभी भी सिर्फ़ success path मत लिखिए। Networks fail होते हैं, servers errors return करते हैं, tokens expire होते हैं, और एक app जो error listener ignore करती है वह users को कुछ गलत होने पर एक frozen या blank screen पर घूरते हुए छोड़ देती है। हर बार error handle कीजिए: एक failed request को एक helpful message produce करना चाहिए, silence नहीं। Success और failure दोनों request का हिस्सा हैं।

Quiz

FestConnect Mobile में, events list fetch करना बनाम API को एक नई registration submit करना, respectively कौन से HTTP methods इस्तेमाल करते हैं?

  1. Fetch करने के लिए POST, submit करने के लिए GET
  2. Events fetch करने के लिए (पढ़ना) GET, और registration submit करने के लिए (create/send) POST
  3. दोनों GET इस्तेमाल करते हैं
  4. दोनों DELETE इस्तेमाल करते हैं
Show the answer

Events fetch करने के लिए (पढ़ना) GET, और registration submit करने के लिए (create/send) POST

Events list fetch करना (पढ़ना) एक GET request है, और एक नई registration submit करना (create/send करना) एक POST request है, REST conventions match करते हुए: GET पढ़ता है, POST create/sends करता है। Option A इन्हें reverse करता है, जो methods का misuse होता (आप सिर्फ़ पढ़ने के लिए POST नहीं करते, न ही नया data भेजने के लिए GET)। Option C wrong है: एक registration submit करना कुछ create करने के लिए data भेजता है, जो GET नहीं POST है। Option D wrong है: DELETE एक resource remove करता है, न fetching न submitting। Method को intent से match कीजिए: data fetch करने के लिए GET, data send/create करने के लिए POST, और callbacks में success और error दोनों handle कीजिए।

Think first

आपको हमेशा Error Case क्यों Handle करना पड़ता है, सिर्फ़ Success नहीं?

Happy path testing में काम करता है। Error listener handle करना success listener जितना ही important क्यों है? फिर tap कीजिए।

Show the answer

क्योंकि network requests real world में regularly FAIL होते हैं, और एक app जो सिर्फ़ success handle करती है users को confused, stuck, या एक broken screen पर घूरते हुए छोड़ती है जब भी कुछ गलत होता है, जो अक्सर होता है। एक fast, reliable connection पर development के दौरान, happy path ही सब कुछ लगता है जो matter करता है, request succeed होती है, आप data दिखाते हैं, done। पर real users flaky mobile networks पर होते हैं, tunnels में, expired tokens के साथ, temporarily down, overloaded, या errors return करने वाले servers पर hit करते हुए। इन सब cases में request FAIL होती है, और अगर आपने सिर्फ़ एक success listener लिखा, कुछ नहीं होता: कोई data नहीं दिखता, कोई message नहीं दिखता, spinner शायद हमेशा के लिए spin करता रहे, और user को नहीं पता wait करना है, retry करना है, या give up करना है। यह एक frustrating, broken experience है। Error listener handle करना आपको gracefully respond करने देता है: एक clear message दिखाइए ('Could not load events, check your connection'), एक retry offer कीजिए, loading indicator hide कीजिए, या cached data पर fall back कीजिए। आप response को tailor करने के लिए एक status code के लिए VolleyError inspect भी कर सकते हैं (401 का मतलब session expire हो गया, तो re-login prompt कीजिए; 404 का मतलब resource gone है; एक network error का मतलब connectivity issue है)। Robust apps failure को एक NORMAL, expected outcome की तरह treat करती हैं जिसे handle करना है, एक edge case नहीं जिसे ignore करना है। यही same discipline है जो आपने Firebase auth errors और Task failures के साथ मिली: हमेशा दोनों outcomes handle कीजिए। Users एक app को judge करते हैं कि यह गलत होने पर कैसे behave करती है, तो errors को अच्छी तरह handle करना optional polish नहीं है, यह core quality है। Failure के लिए plan कीजिए; यह होगा।

Summary

Key takeaways

  • GET एक endpoint से data fetch करता है; POST इसे data भेजता है, दो everyday API calls।
  • एक GET (Request.Method.GET, null body) JSON return करता है जिसे आप success listener में parse और display करते हैं।
  • एक POST (Request.Method.POST एक JSONObject body के साथ) data भेजता है जिसे server process करता है, और respond करता है।
  • दोनों एक success listener (data इस्तेमाल/parse कीजिए) और एक error listener (failures handle कीजिए) लेते हैं।
  • हमेशा दोनों outcomes handle कीजिए: error पर, एक clear message दिखाइए और optionally एक status code के लिए VolleyError inspect कीजिए।
  • यह REST (methods), JSON parsing, और Volley को Android से real API calls में साथ tie करता है।
  • Memory hook: fetch करने के लिए GET, send करने के लिए POST; हर बार success AND error handle कीजिए।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Working with Data and API in Android

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Creating GET and POST request in android; API response handling · Advance Mobile Application Development - II (Major-15-02) · Gri-Learn