vainquit
vainquit

Reputation: 587

How can I retrieve the response from an http get request in Java WITHOUT BufferedReader

I know there are thousands of articles and Q&A which teach me how to send an HTTP request in Java. But all of them use a BufferedReader to read the response from server.

I don't want to use a BufferedReader, because I encountered an "OutOfMemoryError" when using it on my android project. I don't know why this happened while others succeed, but it was certainly caused by BufferedReader after a long time of debugging and I am really tired of this issue. Is there any way to retrieve the response other than creating a new BufferedReader object? I just want to send a simplest get request, and get the response which provides HTML content,not considering efficiency.

Upvotes: 0

Views: 1090

Answers (3)

Java_Herobrine
Java_Herobrine

Reputation: 60

You can use InputStream
E.g:

HttpURLConnection conn=(HttpURLConnection)(new URL(your URL).openConnection());
InputStream is=conn.getInputStream();
String str=new String(is.readAllBytes());
is.close();
return str;

Or Java 11 HttpClient API.
E.g:

HttpClient client=HttpClient.newHttpClient();
HttpRequest request=HttpRequest.newBuilder().uri(new URI(your URL)).GET().build();
HttpResponse<String> response=client.send(request,BodyHandlers.ofString());
return response.body();

Upvotes: 0

Basu
Basu

Reputation: 763

You can use Volley for that. It's fast, fluid and lightweight.

In your build.gradle file, add this line and compile:

implementation 'com.android.volley:volley:1.1.1'

Make a network singleton

public class NetworkSingleton {
    private static NetworkSingleton instance;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;
    private static Context ctx;

    private NetworkSingleton(Context context) {
        ctx = context;
        requestQueue = getRequestQueue();

        imageLoader = new ImageLoader(requestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized NetworkSingleton getInstance(Context context) {
        if (instance == null) {
            instance = new NetworkSingleton(context);
        }
        return instance;
    }

    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
        }
        return requestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}

Make a String Request:

StringRequest stringRequest = new StringRequest(Request.Method.GET, "URL to fetch",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                       //This is executed after successful response to URL
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //If error occurs
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String>  params = new HashMap<String, String>();
                params.put("Authorization", "Add a header to request");

                return params;
            }
        };

        NetworkSingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);

Read more about volley at:

https://developer.android.com/training/volley

Upvotes: 1

Barungi Stephen
Barungi Stephen

Reputation: 847

Use OkHttp for efficient network access

What is OkHTTP? OkHTTP is an open source project designed to be an efficient HTTP client.

// avoid creating several instances, should be singleon
OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
                     .url("https://www.vogella.com/index.html")
                     .build();

You can also add parameters

HttpUrl.Builder urlBuilder = HttpUrl.parse("https://api.github.help").newBuilder();
urlBuilder.addQueryParameter("v", "1.0");
urlBuilder.addQueryParameter("user", "vogella");
String url = urlBuilder.build().toString();

Request request = new Request.Builder()
                     .url(url)
                     .build();

source https://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html

Upvotes: 1

Related Questions