Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;

public class Main {

    public static void main(String args[]) throws Exception {
        String sessionCookie = null;
        URL url = new java.net.URL("http://127.0.0.1/yourServlet");
        URLConnection con = url.openConnection();
        if (sessionCookie != null) {
            con.setRequestProperty("cookie", sessionCookie);
        }
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setDoInput(true);
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(byteOut);
        out.flush();
        byte buf[] = byteOut.toByteArray();
        con.setRequestProperty("Content-type", "application/octet-stream");
        con.setRequestProperty("Content-length", "" + buf.length);
        DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
        dataOut.write(buf);
        dataOut.flush();
        dataOut.close();
        DataInputStream in = new DataInputStream(con.getInputStream());
        int count = in.readInt();
        in.close();
        if (sessionCookie == null) {
            String cookie = con.getHeaderField("set-cookie");
            if (cookie != null) {
                sessionCookie = parseCookie(cookie);
                System.out.println("Setting session ID=" + sessionCookie);
            }
        }

        System.out.println(count);
    }

    public static String parseCookie(String raw) {
        String c = raw;

        if (raw != null) {
            int endIndex = raw.indexOf(";");
            if (endIndex >= 0) {
                c = raw.substring(0, endIndex);
            }
        }
        return c;
    }
}