एंड्रॉइड में Volley लाइब्रेरी से सिंपल HTTP रिक्वेस्ट
यह ट्यूटोरियल दिखाता है कि Volley लाइब्रेरी का उपयोग करके सरल GET रिक्वेस्ट कैसे करें और JSON रिस्पॉन्स को TextView में प्रदर्शित करें।
निर्भरताएं (build.gradle)
dependencies {
implementation 'com.android.volley:volley:1.2.1'
implementation 'androidx.appcompat:appcompat:1.6.1'
}
चरण 1: प्रोजेक्ट बनाएं
नया प्रोजेक्ट बनाएं और Volley निर्भरता जोड़ें।
चरण 2: लेआउट (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/fetchButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="डेटा प्राप्त करें (GET)"
android:layout_marginBottom="16dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/responseText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:fontFamily="monospace"
android:padding="16dp"
android:background="#F5F5F5"
android:text="रिस्पॉन्स यहां दिखेगा..."/>
</ScrollView>
</LinearLayout>
चरण 3: एक्टिविटी कोड (src/MainActivity.java)
package com.example.volleysimple;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
public class MainActivity extends AppCompatActivity {
private TextView responseText;
private Button fetchButton;
private RequestQueue queue;
// टेस्ट API - JSONPlaceholder
private static final String URL = "https://jsonplaceholder.typicode.com/posts/1";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseText = findViewById(R.id.responseText);
fetchButton = findViewById(R.id.fetchButton);
queue = Volley.newRequestQueue(this);
fetchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fetchData();
}
});
}
private void fetchData() {
fetchButton.setEnabled(false);
fetchButton.setText("लोड हो रहा है...");
responseText.setText("रिक्वेस्ट भेजी जा रही है...");
StringRequest request = new StringRequest(
Request.Method.GET,
URL,
new Response.Listener() {
@Override
public void onResponse(String response) {
// सफल रिस्पॉन्स
responseText.setText(prettyPrintJson(response));
fetchButton.setEnabled(true);
fetchButton.setText("डेटा प्राप्त करें (GET)");
Toast.makeText(MainActivity.this, "सफल!", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// त्रुटि हैंडलिंग
String errorMsg = "त्रुटि: ";
if (error.networkResponse != null) {
errorMsg += "HTTP " + error.networkResponse.statusCode + " ";
}
errorMsg += error.getMessage();
responseText.setText(errorMsg);
fetchButton.setEnabled(true);
fetchButton.setText("डेटा प्राप्त करें (GET)");
Log.e("VOLLEY", "रिक्वेस्ट त्रुटि", error);
}
}
) {
// वैकल्पिक: हेडर्स जोड़ें
@Override
public java.util.Map getHeaders() {
java.util.Map headers = new java.util.HashMap<>();
headers.put("User-Agent", "Android-Volley/1.0");
headers.put("Accept", "application/json");
return headers;
}
};
// रीट्राय पॉलिसी
request.setRetryPolicy(new com.android.volley.DefaultRetryPolicy(
15000, // 15 सेकंड टाइमआउट
2, // अधिकतम 2 रीट्राय
2f // बैकऑफ गुणक
));
// रिक्वेस्ट टैग (कैंसिलेशन के लिए)
request.setTag("GET_REQUEST");
queue.add(request);
}
// JSON प्रिटी प्रिंट (सरल)
private String prettyPrintJson(String json) {
try {
// Gson या JSONObject से फॉर्मेट करें
org.json.JSONObject obj = new org.json.JSONObject(json);
return obj.toString(4); // 4 स्पेस इंडेंट
} catch (Exception e) {
return json; // पहले से फॉर्मेटेड नहीं तो मूल लौटाएं
}
}
@Override
protected void onStop() {
super.onStop();
// एक्टिविटी रुकने पर पेंडिंग रिक्वेस्ट कैंसिल करें
queue.cancelAll("GET_REQUEST");
}
}
चरण 4: मैनिफेस्ट (AndroidManifest.xml)
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.volleysimple">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application ...>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Volley रिक्वेस्ट प्रकार
| क्लास | उपयोग |
|---|---|
StringRequest | सादा टेक्स्ट/JSON/HTML रिस्पॉन्स |
JsonObjectRequest | सीधे JSONObject रिस्पॉन्स |
JsonArrayRequest | सीधे JSONArray रिस्पॉन्स |
ImageRequest | इमेज डाउनलोड |
Custom Request | POST/PUT/DELETE, कस्टम बॉडी |
POST रिक्वेस्ट उदाहरण
StringRequest postRequest = new StringRequest(
Request.Method.POST,
"https://api.example.com/endpoint",
response -> { /* सफलता */ },
error -> { /* त्रुटि */ }
) {
@Override
protected java.util.Map getParams() {
java.util.Map params = new java.util.HashMap<>();
params.put("username", "user123");
params.put("password", "secret");
return params;
}
@Override
public java.util.Map getHeaders() {
java.util.Map headers = new java.util.HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Authorization", "Bearer token123");
return headers;
}
};
Volley सर्वोत्तम अभ्यास
- सिंगलटन RequestQueue: एप्लिकेशन क्लास में एक इंस्टेंस बनाएं
- इमेज लोडिंग:
ImageLoaderयाNetworkImageViewउपयोग करें - कैशिंग: Volley स्वचालित कैशिंग करता है (HTTP हेडर्स आधारित)
- कैंसिलेशन:
queue.cancelAll(tag)याrequest.cancel() - थ्रेडिंग: नेटवर्क वर्कर थ्रेड पर, कॉलबैक मेन थ्रेड पर
Application क्लास में सिंगलटन क्यू
public class MyApp extends Application {
private static MyApp instance;
private RequestQueue requestQueue;
public static MyApp getInstance() { return instance; }
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
// उपयोग: MyApp.getInstance().getRequestQueue().add(request);
चरण 5: टेस्ट करें
- ऐप चलाएं (इंटरनेट आवश्यक)
- "डेटा प्राप्त करें" बटन दबाएं
- JSON रिस्पॉन्स फॉर्मेटेड दिखेगा
- नेटवर्क बंद करके त्रुटि हैंडलिंग टेस्ट करें
