Search code examples
androidapachehttp

Best way to perform a GET request without any other libraries


It looks like the Apache client is deprecated. Is there another way to make an http request without installing fancy libraries?

Should I use the Apache client anyway? How do I import it? My Android Studio does not want to import HttpClient, HttpGet, ...


Solution

  • Have you tried HttpURlConnection?

    Here's a sample code that get the image from a server and displaying it to a Image view:

    private class SendHttpRequestTask extends AsyncTask<String, Void, Bitmap> {
                @Override
                protected Bitmap doInBackground(String... params) {
                    try {
                        URL url = new URL("http://xxx.xxx.xxx/image.jpg");
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setDoInput(true);
                        connection.connect();
                        InputStream input = connection.getInputStream();
                        Bitmap myBitmap = BitmapFactory.decodeStream(input);
                        return myBitmap;
                    }catch (Exception e){
                        Log.e(TAG,e.getMessage());
                    }
                    return null;
                }
    
                @Override
                protected void onPostExecute(Bitmap result) {
                        ImageView imageView = (ImageView) findViewById(ID OF YOUR IMAGE VIEW);
                        imageView.setImageBitmap(result);
                }
        }
    

    I hope i could help