Get cookie from http via HttpURLConnection - Java Network

Java examples for Network:URL Download

Description

Get cookie from http via HttpURLConnection

Demo Code



import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.zip.GZIPInputStream;

public class HttpCookie {

    public static void main(String[] args) {
        String webPage = "http://your server/login/login";
        try {/*w  ww.  j  a  v  a 2s.c o  m*/
            URL url = new URL(webPage);
            HttpURLConnection con = (HttpURLConnection) url
                    .openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Accept-Language",
                    "ko,en-US;q=0.7,en;q=0.3");

            String name = "admin";
            String password = "admin";
            String auth = name + ":" + password;

            String authStringEnc = Base64.getEncoder().encodeToString(
                    auth.getBytes());
            System.out.println("Base64 encoded auth string:"
                    + authStringEnc);
            con.setRequestProperty("Authorization", "Basic "
                    + authStringEnc);

            con.setConnectTimeout(5000);
            con.setReadTimeout(5000);
            con.connect();

            int status = con.getResponseCode();
            if (HttpURLConnection.HTTP_OK == status) {
                InputStream is = con.getInputStream();
                String encode = con.getContentEncoding();
                if (encode != null && encode.equalsIgnoreCase("gzip")) {
                    is = new GZIPInputStream(is);
                }
                InputStreamReader isr = new InputStreamReader(is);
                int numCharsRead = 0;
                char[] charArray = new char[2048];
                StringBuffer sb = new StringBuffer();
                while ((numCharsRead = isr.read(charArray)) > 0) {
                    sb.append(charArray, 0, numCharsRead);
                }

                String r = sb.toString();
                System.out.println("-----start------------");
                System.out.println(sb);
                System.out.println("-----end ------------");
                is.close();
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Related Tutorials