URLConnection is a java class used to connect to a URL and perform reads and writes.

Uses of URLConnection

Well, connect to a URL then write to or read from it.

Characteristics of URLConnection class

  1. First it belongs to java.net package.
  2. It’s an abstract class:
    public abstract class URLConnection..{}
  3. It derives from java.lang.Object:
    public abstract class URLConnection extends Object{}

URLConnection children

This class has several children:

Class Type Description
HttpURLConnection Direct URLConnection for HTTP.
JarURLConnection Direct URLConnection for jars
HttpsURLConnection Indirect This is the HttpURLConnection for HTTPS.

Examples

1. How to Open a URL Connection
    private static URLConnection open(String url, String auth) throws MalformedURLException, IOException {
        URLConnection conn = new URL(url).openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setRequestProperty("Content-Type", contentType);
        if (auth != null) {
            conn.setRequestProperty("Authorization", auth);
        }
        return conn;
    }

Example 1

Make a HTTP GET request in Java:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLConnectionGet {

	public static void main(String[] args) throws IOException {
		
		URL url = new URL("http://www.w3school.com.cn/b.asp");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
		
		conn.setDoInput(true);  
		conn.setRequestMethod("GET");  		conn.setRequestMethod("POST"); 
		conn.connect();  
		int statusCode = conn.getResponseCode(); 
		String responseBody = null;
		if (HttpURLConnection.HTTP_OK == statusCode) { 
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(conn.getInputStream(), "GBK"));  BufferedReader
			String readLine = null;
			StringBuffer response = new StringBuffer();
			while (null != (readLine = bufferedReader.readLine())) {
				response.append(readLine);
			}

			bufferedReader.close();
			responseBody = response.toString();
		}
		System.out.println(responseBody);
	}
}

Example 2

The second example examines how to make set a http header:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionHeaderSet {
	public static void main(String[] args) throws IOException {
		
		URL url = new URL("http://www.w3school.com.cn/b.asp");
		URLConnection conn =  url.openConnection(); 
		//HttpURLConnection conn = (HttpURLConnection) url.openConnection()
		
		conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");  
		conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9"); 
		conn.setRequestProperty("Host", "www.w3school.com.cn"); 
		conn.setRequestProperty("Cache-Control", "max-age=0"); 
		conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36"); 
		conn.connect();

		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(conn.getInputStream(), "gbk"));
		String line; 
		String html = "";
		while ((line = bufferedReader.readLine()) != null) {  
			html +=  line;  
		}  
		System.out.println(html);
	}
}

Example 3 – HTTP POST example

The third example is a URLConnection POST example in Java:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLConnectionPost {

	public static void main(String[] args) throws IOException {
		
		String wen = "EH629625211CS";
		String action = "ajax";
		
		URL url = new URL("http://www.kd185.com/ems.php");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
		conn.setDoOutput(true);  
		conn.setRequestMethod("POST");
		StringBuffer params = new StringBuffer();  
		
		params.append("wen").append("=").append(wen).append("&")
		.append("action").append("=").append(action);
		byte[] bypes = params.toString().getBytes();
		conn.getOutputStream().write(bypes);
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(conn.getInputStream(), "utf-8"));  
		String line; 
		String html = "";
		while ((line = bufferedReader.readLine()) != null) {  
			html +=  line;  
		}  
		System.out.println(html);
	}
}

Example 4 -Proxy Example

This is the fourth example also in java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionProxy {
	public static void main(String[] args) throws IOException {
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("171.97.67.160", 3128));  //设置代理
		URL url = new URL("http://www.w3school.com.cn/b.asp");  
		URLConnection conn = url.openConnection(proxy);  
		conn.connect(); 
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(conn.getInputStream(), "gbk")); 
		String line; 
		String html = "";
		while ((line = bufferedReader.readLine()) != null) {  
			html +=  line;  
		}  
		System.out.println(html);
	}
}

 

Example 5 – TimeOut Example

The 5th example is a connection timeout example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionTimeOut {
	public static void main(String[] args) throws IOException {
		
		URL url = new URL("http://www.w3school.com.cn/b.asp");
		URLConnection conn =  url.openConnection(); 
//		HttpURLConnection conn = (HttpURLConnection) url.openConnection()
		
		conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");  
		conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9"); 
		conn.setRequestProperty("Host", "www.w3school.com.cn"); 
		conn.setRequestProperty("Cache-Control", "max-age=0"); 
		conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36"); 
		conn.setConnectTimeout(30000);  
		conn.setReadTimeout(30000);  
		conn.connect();

		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(conn.getInputStream(), "gbk"));
		String line; 
		String html = "";
		while ((line = bufferedReader.readLine()) != null) {  
			html +=  line;  
		}  
		System.out.println(html);
	}
}

Example 6 – Download PDF

The sixth URLConnection example involves downloading a PDF file:

import java.io.*;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        System.out.println("Connecting...");
        try {
            String u = "https://www.cs.usfca.edu/~parrt/doc/java/JavaIO-notes.pdf";
            URL url = new URL(u);
            InputStream in = url.openStream();
            FileOutputStream fileOutputStream = new FileOutputStream(new File("io_notes.pdf"));
            System.out.println("Connected");
            int length = -1;
            byte[] buffer = new byte[1024];
            System.out.println("Downloading...");
            while ((length = in.read(buffer)) > -1) {
                fileOutputStream.write(buffer, 0, length);
            }
            fileOutputStream.close();
            in.close();
            System.out.println("Process finished");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Android Example  1

Here is a URLConnection example with androiod.

Create an android project.

Go to MainActivity and add the following imports

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

Extend the asynctask class:

    public class DownloadTask extends AsyncTask<String,Void,String>{

Override the doInBackground method and do the stuff there:

        @Override
        protected String doInBackground(String... urls) {

            String result="";
            URL url;
            HttpURLConnection urlConnection=null;

            try {
                url=new URL(urls[0]);
                urlConnection=(HttpURLConnection) url.openConnection();
                InputStream inputStream=urlConnection.getInputStream();
                InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
                int data=inputStreamReader.read();
                while (data!=-1){
                    char current=(char)data;
                    result += current;
                    data=inputStreamReader.read();
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                return  "Failed";
            }
        }

 

Here is the full class:

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

    public class DownloadTask extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... urls) {

            String result="";
            URL url;
            HttpURLConnection urlConnection=null;

            try {
                url=new URL(urls[0]);
                urlConnection=(HttpURLConnection) url.openConnection();
                InputStream inputStream=urlConnection.getInputStream();
                InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
                int data=inputStreamReader.read();
                while (data!=-1){
                    char current=(char)data;
                    result += current;
                    data=inputStreamReader.read();
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                return  "Failed";
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DownloadTask downloadTask=new DownloadTask();
        String result=null;
        try {
            result=downloadTask.execute("https://www.google.com/gmail/").get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        Log.i("Contents of URL ",result);
    }
}

This example was created by @owaisalam12.

Download Full Example.

Android Example 2 – Movie App

This is also an android app based on URLConnection/HttpURLConnection.

Start by creating a movie model class:

public class MovieModel {

    private String movie;
    private int year;
    private float rating;
    private String duration;
    private String director;
    private String tagline;
    private String image;
    private String story;
    private List castList;


    public String getMovie() {
        return movie;
    }

    public void setMovie(String movie) {
        this.movie = movie;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public float getRating() {
        return rating;
    }

    public void setRating(float rating) {
        this.rating = rating;
    }

    public String getDuration() {
        return duration;
    }

    public void setDuration(String duration) {
        this.duration = duration;
    }

    public String getDirector() {
        return director;
    }

    public void setDirector(String director) {
        this.director = director;
    }

    public String getTagline() {
        return tagline;
    }

    public void setTagline(String tagline) {
        this.tagline = tagline;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getStory() {
        return story;
    }

    public void setStory(String story) {
        this.story = story;
    }

    public List getCastList() {
        return castList;
    }

    public void setCastList(List castList) {
        this.castList = castList;
    }

    public static class Cast {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

Now come to the MainActivity:

public class MainActivity extends AppCompatActivity {

    private final String URL_CONNECT = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesData.txt";

    private ListView lvMovies;


    //1 https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt
    //2 https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt
    //3 https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesData.txt

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lvMovies = (ListView) findViewById(R.id.lvMovies);

        Button btnRefresh = (Button) findViewById(R.id.btnRefresh);

        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JSONTASK().execute(URL_CONNECT);
            }
        });

//                new JSONTASK().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
    }

    private class JSONTASK extends AsyncTask<String, String, List> {

        @Override
        protected List doInBackground(String... urls) {
            HttpURLConnection connection = null;
            BufferedReader reader = null;
            try {
                URL url = new URL(urls[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();

                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }

                String finalJson = buffer.toString();

                JSONObject parentObject = new JSONObject(finalJson);
                JSONArray parentArray = parentObject.getJSONArray("movies");


                List movieModelList = new ArrayList<>();

                    for(int i=0; i<parentArray.length(); i++) {
                        MovieModel movieModel = new MovieModel();
                        JSONObject finalObject = parentArray.getJSONObject(i);

                        movieModel.setMovie(finalObject.getString("movie"));
                        movieModel.setYear(finalObject.getInt("year"));
                        movieModel.setRating((float) finalObject.getDouble("rating"));
                        movieModel.setDirector(finalObject.getString("director"));

                        movieModel.setDuration(finalObject.getString("duration"));
                        movieModel.setTagline(finalObject.getString("tagline"));
                        movieModel.setImage(finalObject.getString("image"));
                        movieModel.setStory(finalObject.getString("story"));

                        List castList = new ArrayList<>();
                        for(int j=0; j<finalObject.getJSONArray("cast").length(); j++){
                            MovieModel.Cast cast = new MovieModel.Cast();
                            cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
                            castList.add(cast);
                        }
                        movieModel.setCastList(castList);
                        movieModelList.add(movieModel);
                    }
                return movieModelList;
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            } finally {
                if (connection != null)
                    connection.disconnect();
                try {
                    if (reader != null)
                        reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            return null;
        }

        @Override
        protected void onPostExecute(final List result) {
            super.onPostExecute(result);
            if(result != null) {
                MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, result);
                lvMovies.setAdapter(adapter);
            } else {
                Toast.makeText(getApplicationContext(), "Not able to fetch data from server, please check url.", Toast.LENGTH_SHORT).show();
            }
        }
    }


    public class MovieAdapter extends ArrayAdapter{

        private List movieModelList;
        private int resource;
        private LayoutInflater inflater;
        public MovieAdapter(Context context, int resource, List objects) {
            super(context, resource, objects);
            movieModelList = objects;
            this.resource = resource;
            inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;

            if(convertView == null){
                holder = new ViewHolder();
                convertView = inflater.inflate(resource, null);
                holder.ivMovieIcon = (ImageView)convertView.findViewById(R.id.ivIcon);
                holder.tvMovie = (TextView)convertView.findViewById(R.id.movieName);
                holder.tvTagline = (TextView)convertView.findViewById(R.id.tagLine);
                holder.tvYear = (TextView)convertView.findViewById(R.id.year);
                holder.tvDuration = (TextView)convertView.findViewById(R.id.duration);
                holder.tvDirector = (TextView)convertView.findViewById(R.id.director);
                holder.rbMovieRating = (RatingBar)convertView.findViewById(R.id.ratingBar);
                holder.tvCast = (TextView)convertView.findViewById(R.id.tvCast);
                holder.tvStory = (TextView)convertView.findViewById(R.id.story);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            // Then later, when you want to display image
            final ViewHolder finalHolder = holder;

            holder.tvMovie.setText(movieModelList.get(position).getMovie());
            holder.tvTagline.setText(movieModelList.get(position).getTagline());
            holder.tvYear.setText("Year: " + movieModelList.get(position).getYear());
            holder.tvDuration.setText("Duration:" + movieModelList.get(position).getDuration());
            holder.tvDirector.setText("Director:" + movieModelList.get(position).getDirector());

            // rating bar
            holder.rbMovieRating.setRating(movieModelList.get(position).getRating()/2);

            StringBuffer stringBuffer = new StringBuffer();
            for(MovieModel.Cast cast : movieModelList.get(position).getCastList()){
                stringBuffer.append(cast.getName() + ", ");
            }

            holder.tvCast.setText("Cast:" + stringBuffer);
            holder.tvStory.setText(movieModelList.get(position).getStory());
            return convertView;
        }


        class ViewHolder{
            private ImageView ivMovieIcon;
            private TextView tvMovie;
            private TextView tvTagline;
            private TextView tvYear;
            private TextView tvDuration;
            private TextView tvDirector;
            private RatingBar rbMovieRating;
            private TextView tvCast;
            private TextView tvStory;
        }

    }


}

This example was created by  @Andrzej1991 .

Download the full example.

Android Example 3

The third android example involves HttpURLConnection, Thread class and runOnUIThread:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private Button btn_check;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private void initViews() {
        btn_check= (Button) findViewById(R.id.btn);
        textView= (TextView) findViewById(R.id.tv);

        btn_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL url=new URL("http://v.juhe.cn/exp/index?com=tt&no=667300323472&dtype=&key=b2725a94f8d23467e1b8804be164b719");
                            HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                            InputStream is=conn.getInputStream();
                            BufferedReader br=new BufferedReader(new InputStreamReader(is,"utf-8"));
                            StringBuffer buffer=new StringBuffer();
                            String line=br.readLine();
                            while(line!=null){
                                buffer.append(line);
                                line=br.readLine();
                            }
                            final String webContent=buffer.toString();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    textView.setText(webContent);
                                }
                            });

                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();


            }
        });
    }
}