Results 1 to 7 of 7
  1. #1
    rhexis is offline Member
    Join Date
    Nov 2011
    Posts
    56
    Rep Power
    0

    Default Unable to connect to my localhost webserver through .jar file.

    Good evening.

    I've encountered a problem running my .jar file.

    I have a Login.jar file as well as a WebServer.jar file that I've exported through Eclipse.

    My WebServer.jar file runs perfectly fine. However, when I execute my Login.jar file, I'm getting the following error.

    Java Code:
    java.io.IOException: Invalid Http response
            at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
            at java.net.URL.openStream(Unknown Source)
            at LoginFrame$1.run(LoginFrame.java:74)
            at java.awt.event.InvocationEvent.dispatch(Unknown Source)
            at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
            at java.awt.EventQueue.access$200(Unknown Source)
            at java.awt.EventQueue$3.run(Unknown Source)
            at java.awt.EventQueue$3.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
            at java.awt.EventQueue.dispatchEvent(Unknown Source)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
            at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.run(Unknown Source)
    I have already placed the required file inside the same folder as both my .jar files. I know it has something to do with my LoginFrame.jar because if I run my WebServer.jar file, I am able to connect to it through running LoginFrame from Eclipse itself. However, running it through the command line gives me the above error.

    My WebServer is displaying

    Java Code:
    GET /login.json HTTP/1.1
    HTTP/1.0 200 OK
    
    Content-type: application/octet-stream
    
    
    
    *****
    ./login.json
    *****
    so that means that the file is in place.


    The following is my LoginFrame code.

    Java Code:
    import java.awt.EventQueue;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.JPasswordField;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.UIManager;
    import javax.swing.UIManager.LookAndFeelInfo;
    import java.awt.Font;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.util.ArrayList;
    import net.sf.json.JSONObject;
    import net.sf.json.JSONSerializer;
    
    public class LoginFrame extends JFrame {
    
    	private JPanel contentPane;
    	private JTextField textField;
    	private JPasswordField passwordField;
    	private String NRIC;
    	private String password;
    	private String name;
    	private static String host = "http://localhost:9999/login.json";
    	private SCDFLifeMainFrame newSCDFLifeMainFrame;
    
    	private static ArrayList listOfNRIC;
    	private static ArrayList listOfPassword;
    	private static ArrayList listOfName;
    	private JSONObject json;
    	private static String line;
    
    	/**
    	 * Launch the application.
    	 * 
    	 * @throws IOException
    	 */
    	public static void main(String[] args) throws IOException {
    		listOfNRIC = new ArrayList();
    		listOfPassword = new ArrayList();
    		listOfName = new ArrayList();
    		try {
    			for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
    				if ("Nimbus".equals(info.getName())) {
    					UIManager.setLookAndFeel(info.getClassName());
    					break;
    				}
    			}
    		} catch (Exception e) {
    			// If Nimbus is not available, you can set the GUI to another look
    			// and feel.
    		}
    
    		
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					System.out.println("TEST");
    					LoginFrame frame = new LoginFrame();
    
    					frame.setVisible(true);
    
    					URL url = new URL(host);
    
    					BufferedReader reader = new BufferedReader(
    							new InputStreamReader(url.openStream()));
    					while ((line = reader.readLine()) != null) {
    						JSONObject json = (JSONObject) JSONSerializer
    								.toJSON(line);
    						String loginNRIC = json.getString("NRIC");
    
    						String loginPassword = json.getString("PASSWORD");
    						String loginName = json.getString("NAME");
    						listOfNRIC.add(loginNRIC);
    						listOfPassword.add(loginPassword);
    						listOfName.add(loginName);
    					}
    
    				} catch (Exception e) {
    					e.printStackTrace();
    					JOptionPane
    							.showMessageDialog(
    									null,
    									"Connection Refused. Check internet connection or server status.",
    									"Connection Refused",
    									JOptionPane.WARNING_MESSAGE);
    
    				}
    			}
    		});
    	}
    
    	/**
    	 * Create the frame.
    	 */
    	public LoginFrame() {
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setBounds(100, 100, 450, 300);
    		contentPane = new JPanel();
    		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    		setContentPane(contentPane);
    		contentPane.setLayout(null);
    
    		JPanel panel = new JPanel();
    		panel.setBounds(123, 94, 188, 125);
    		contentPane.add(panel);
    		panel.setLayout(null);
    
    		textField = new JTextField();
    		textField.setBounds(80, 0, 108, 31);
    		panel.add(textField);
    		textField.setColumns(10);
    
    		passwordField = new JPasswordField();
    		passwordField.setBounds(80, 42, 108, 31);
    		panel.add(passwordField);
    
    		JButton btnNewButton = new JButton("Login");
    		btnNewButton.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent arg0) {
    
    				NRIC = textField.getText();
    				password = passwordField.getText();
    
    				if (listOfNRIC.size() > 0) {
    					for (int i = 0; i < listOfNRIC.size(); i++) {
    						if (NRIC.equals(listOfNRIC.get(i))) {
    							if (password.equals(listOfPassword.get(i))) {
    								JOptionPane.showMessageDialog(null,
    										"Login Successful.", "Login",
    										JOptionPane.INFORMATION_MESSAGE);
    								newSCDFLifeMainFrame = new SCDFLifeMainFrame();
    								newSCDFLifeMainFrame.setVisible(true);
    								setVisible(false);
    								dispose();
    							} else {
    								JOptionPane.showMessageDialog(null,
    										"Wrong Login. Check NRIC/Password.",
    										"Login Failed.",
    										JOptionPane.WARNING_MESSAGE);
    							}
    						}
    					}
    				} else {
    					JOptionPane.showMessageDialog(null, "Failed.", "Failed.",
    							JOptionPane.WARNING_MESSAGE);
    				}
    			}
    
    		});
    
    		btnNewButton.setBounds(48, 102, 89, 23);
    		panel.add(btnNewButton);
    
    		JLabel lblNric = new JLabel("NRIC:");
    		lblNric.setBounds(0, 8, 70, 14);
    		panel.add(lblNric);
    		lblNric.setFont(new Font("Calibri", Font.PLAIN, 14));
    
    		JLabel lblPassword = new JLabel("Password:");
    		lblPassword.setBounds(0, 50, 70, 14);
    		panel.add(lblPassword);
    		lblPassword.setFont(new Font("Calibri", Font.PLAIN, 14));
    
    		ImageIcon myImage = new ImageIcon("paramedic-symbol.jpg");
    		JLabel label = new JLabel(myImage);
    		label.setBounds(5, 5, 75, 75);
    		contentPane.add(label);
    
    		JLabel lblScdfLife = new JLabel("SCDF LIFE");
    		lblScdfLife.setBounds(166, 38, 102, 23);
    		lblScdfLife.setFont(new Font("Calibri", Font.BOLD, 24));
    		contentPane.add(lblScdfLife);
    
    		setLocationRelativeTo(null);
    	}
    }

    I would appreciate if I anyone can guide me on this.
    Last edited by rhexis; 04-16-2013 at 07:49 PM.

  2. #2
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    757
    Rep Power
    8

    Default Re: Unable to connect to my localhost webserver through .jar file.

    I assume the error was caused by your content type: Content-type: application/octet-stream. Try to use Content-type: application/json instead. Are you trying to write your own web server? Why don't you simply use tomcat, jetty or apache?

  3. #3
    rhexis is offline Member
    Join Date
    Nov 2011
    Posts
    56
    Rep Power
    0

    Default Re: Unable to connect to my localhost webserver through .jar file.

    Hello again wsaryada. Yes, I believe it has something to do with the content type as well.

    Because if I changed my host to yahoo.com, I am able to run my .jar file. However, the .json file produces the above error. What I am confused is why am I able to run the codes in eclipse with no problem, but the .jar file produces an error.

    I did not really write my own web server. I tried reading up on Jetty but I didn't quite understand it and didn't have time on my hand to read it. So I just managed to get a simple web server through google that can accept a socket connection.

    This is the web server code that I manage to get through http://programwebserver.blogspot.sg/...erverjava.html

    Java Code:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    import javax.swing.JOptionPane;
    
    public final class webserver2 {
    	public static void main(String argv[]) throws Exception {
    		// Set the port number.
    		int port = 9999;
    
    		// Establish the listen socket.
    		ServerSocket welcomeSocket = new ServerSocket(port);
    
    		JOptionPane.showMessageDialog(null, "Connection Started.",
    				"Connection Started.", JOptionPane.WARNING_MESSAGE);
    		// Process HTTP service requests in an infinite loop.
    		while (true) {
    			// Listen for a TCP connection request.
    			Socket connectionSocket = welcomeSocket.accept();
    
    			// Construct an object to process the HTTP request message.
    			HttpRequest request = new HttpRequest(connectionSocket);
    
    			// Create a new thread to process the request.
    			Thread thread = new Thread(request);
    			// Start the thread.
    			thread.start();
    		}
    	}
    }
    
    final class HttpRequest implements Runnable {
    	final static String CRLF = "\r\n";// returning carriage return (CR) and a
    										// line feed (LF)
    	Socket socket;
    
    	// Constructor
    	public HttpRequest(Socket socket) throws Exception {
    		this.socket = socket;
    	}
    
    	// Implement the run() method of the Runnable interface.
    	// Within run(), we explicitly catch and handle exceptions with a try/catch
    	// block.
    	public void run() {
    		try {
    			processRequest();
    		} catch (Exception e) {
    			JOptionPane.showMessageDialog(null, "ERROR1", "ERROR1.",
    					JOptionPane.WARNING_MESSAGE);
    			System.out.println(e);
    		}
    	}
    
    	private void processRequest() throws Exception {
    		// Get a reference to the socket's input and output streams.
    		InputStream instream = socket.getInputStream();
    		DataOutputStream os = new DataOutputStream(socket.getOutputStream());
    
    		// Set up input stream filters.
    		// Page 169 10th line down or so...
    		BufferedReader br = new BufferedReader(new InputStreamReader(instream));// reads
    																				// the
    																				// input
    																				// data
    
    		// Get the request line of the HTTP request message.
    		String requestLine = br.readLine();// get /path/file.html version of
    											// http
    
    		// Display the request line.
    		System.out.println();
    		System.out.println(requestLine);
    		// HERE WE NEED TO DEAL WITH THE REQUEST
    		// Extract the filename from the request line.
    		StringTokenizer tokens = new StringTokenizer(requestLine);// this is a
    																	// input
    																	// method
    																	// with
    																	// deliminators
    		tokens.nextToken(); // skip over the method, which should be "GET"
    		String fileName = tokens.nextToken();
    
    		// Prepend a "." so that file request is within the current directory.
    		fileName = "." + fileName;
    
    		// Open the requested file.
    
    		FileInputStream fis = null;
    		boolean fileExists = true;
    		try {
    			fis = new FileInputStream(fileName);
    		} catch (FileNotFoundException e) {
    			fileExists = false;
    			JOptionPane.showMessageDialog(null, "ERROR2", "ERROR2.",
    					JOptionPane.WARNING_MESSAGE);
    		}
    
    		// Construct the response message.
    		String statusLine = null;
    		String contentTypeLine = null;
    		String entityBody = null;
    
    		if (fileExists) {
    			statusLine = "HTTP/1.0 200 OK" + CRLF; // common success message
    			contentTypeLine = "Content-type: " + contentType(fileName) + CRLF;
    		}// content info
    
    		else {
    			statusLine = "HTTP/1.0 404 Not Found" + CRLF;// common error message
    			contentTypeLine = "Content-type: " + "text/html" + CRLF;// content
    																	// info
    			entityBody = "<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>"
    					+ "<BODY>Not Found</BODY></HTML>";
    			JOptionPane.showMessageDialog(null, "ERROR3", "ERROR3.",
    					JOptionPane.WARNING_MESSAGE);
    		}
    
    		// Send the status line.
    		// os.writeBytes(statusLine);
    		System.out.println(statusLine);
    
    		// Send the content type line.
    		// os.writeBytes(contentTypeLine);
    		System.out.println(contentTypeLine);
    		// Send a blank line to indicate the end of the header lines.
    		// os.writeBytes(CRLF);
    		System.out.println(CRLF);
    		// Send the entity body.
    		if (fileExists) {
    			sendBytes(fis, os);
    			// System.out.println(statusLine);// Send the status line.
    			// System.out.println(contentTypeLine);
    			fis.close();
    		} else {
    			// os.writeBytes(statusLine);// Send the status line.
    			// os.writeBytes(entityBody);// Send the an html error message info
    			// body.
    			// os.writeBytes(contentTypeLine);// Send the content type line.
    		}
    
    		System.out.println("*****");
    		System.out.println(fileName);// print out file request to console
    		System.out.println("*****");
    		// Get and display the header lines.
    		String headerLine = null;
    		while ((headerLine = br.readLine()).length() != 0) {
    			// System.out.println(headerLine);
    		}
    
    		// code from part 1
    		// Right here feed the client something
    		// os.writeBytes("<html><body><h1>My First Heading</h1>");
    		// os.writeBytes( "<p>My first paragraph.</p></body></html> ");
    		// os.flush();
    
    		// Close streams and socket.
    		os.close();
    		br.close();
    		socket.close();
    
    	}
    
    	// return the file types
    	private static String contentType(String fileName) {
    		if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
    			return "text/html";
    		}
    		if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
    			return "image/jpeg";
    		}
    		if (fileName.endsWith(".gif")) {
    			return "image/gif";
    		}
    		return "application/octet-stream";
    	}
    
    	// set up input output streams
    	private static void sendBytes(FileInputStream fis, OutputStream os)
    			throws Exception {
    		// Construct a 1K buffer to hold bytes on their way to the socket.
    		byte[] buffer = new byte[1024];
    		int bytes = 0;
    
    		// Copy requested file into the socket's output stream.
    		while ((bytes = fis.read(buffer)) != -1)// read() returns minus one,
    												// indicating that the end of
    												// the file
    		{
    			os.write(buffer, 0, bytes);
    		}
    	}
    }
    The code does not set any content type, but simply returns a string based on what the file type is. May I know how do I set a content type?




    I just did several other tests and they all resulted in the same error.

    I changed my host to a .html file because I initially thought that maybe .json was the problem. But it returned the same error. I edited my .html file and included <html><body> since I thought maybe it required that to read, but to no avail as well. Just thought I'd update a little.

    Another update. It seems to be that I have to load it as a resource to have it run in .jar file. I'm able to run it using the following code.

    Java Code:
    InputStream inp = ClassLoader.getSystemClassLoader()
    								.getResourceAsStream("login.json");
    however, how am I supposed to connect to my localhost and get this login.json? As of the above code, it is directly getting it off the file's location.
    Last edited by rhexis; 04-17-2013 at 05:47 AM.

  4. #4
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    757
    Rep Power
    8

    Default Re: Unable to connect to my localhost webserver through .jar file.

    After i see the webserver2.java that you post I think the first error was causes because it cannot read the file (login.json). make sure that the file is in the same directory with the webserver.jar so it can read it. You can use the getResourceAsStream() method if you want to.

  5. #5
    rhexis is offline Member
    Join Date
    Nov 2011
    Posts
    56
    Rep Power
    0

    Default Re: Unable to connect to my localhost webserver through .jar file.

    Thanks for your prompt reply.

    Yes, using getResourceAsStream() allows me to get my login.json from my Login.jar

    However, it does not get the login.json from my webserver. It simply gets it from the directory.

    I'm unable to do

    Java Code:
    InputStream inp = ClassLoader.getSystemClassLoader().getResourceAsStream("http://localhost:9999/login.json");
    for example.

    How should I go about converting my url to a resource?
    Last edited by rhexis; 04-17-2013 at 08:11 AM.

  6. #6
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    757
    Rep Power
    8

    Default Re: Unable to connect to my localhost webserver through .jar file.

    In your case the LoginFrame will obtain the resource using the URL right? It is the the job of the webserver.jar to read the content of the login.json and give it to the LoginFrame via URL connection. The LoginFrame will communicate with the webserver.jar URL connection. The LoginFrame technically have no idea where the login.json is stored but the webserver.jar should know where the file is.

  7. #7
    rhexis is offline Member
    Join Date
    Nov 2011
    Posts
    56
    Rep Power
    0

    Default Re: Unable to connect to my localhost webserver through .jar file.

    Sorry I got a little lost there.

    Basically my webserver just allows a socket connection on port 9999.

    In my LoginFrame, it connects to the localhost on port 9999 converts the URL into resource.

    My webserver does know where the login.json is, which is why it prints

    Java Code:
    GET /login.json HTTP/1.1
    HTTP/1.0 200 OK
     
    Content-type: application/octet-stream
     
     
     
    *****
    ./login.json
    *****
    however, my LoginFrame is unable to change the URL into resource.

    Sorry wsaryada, I'm really confused over everything now.

    Are you trying to say that I should put

    Java Code:
    InputStream inp = ClassLoader.getSystemClassLoader()
    							.getResourceAsStream("login.json");
    					BufferedReader rd = new BufferedReader(
    							new InputStreamReader(inp));
    					String s = "";
    					try {
    						while (null != (s = rd.readLine())) {
    							System.out.println(s);
    						}
    					} finally {
    						rd.close();
    					}
    in my webserver class? If so, how do I pass these information to my LoginFrame? Since it is a webserver, they would not be in the same package, and I assume I would not be able to create a method in my webserver to pass these information to my LoginFrame.


    Where should I start changing? Anyway wsaryada, thanks again for your time and help. Appreciate it. If I sound a little off or sound too stupid, do forgive me. I've been working on this project for weeks spending > 10 hours a day so I'm a little fried and frustrated. Thanks!


    EDIT:

    Hey wsaryada. Thanks to you, I finally got it to work through .jar. I understand what you mean now that the webserver is suppose to convert the .json file to readable format for the LoginFrame, and thus manage to do that using a simpler web server I got off google. I edited it a little and manage to get my LoginFrame.jar to work.

    However, the next Frame that calls up gets a hell load of error, so I guess I'm going to stop trouble shooting it.

    I would like to ask if you would be able to help me on another matter. Is there any other alternatives that I am able to execute my java files instead of using .jar? Thank you. :happy:
    Last edited by rhexis; 04-18-2013 at 09:04 AM.

Similar Threads

  1. Unable to connect to ftp server java
    By sagngh8 in forum Networking
    Replies: 1
    Last Post: 12-22-2010, 04:55 AM
  2. unable to connect remote database using jdbc
    By enggvijaysingh@gmail.com in forum Advanced Java
    Replies: 1
    Last Post: 12-16-2010, 12:16 PM
  3. I m unable to connect one frame 2 the other
    By ankitraghuvanshi in forum NetBeans
    Replies: 2
    Last Post: 10-23-2008, 02:24 AM
  4. Replies: 1
    Last Post: 10-21-2008, 09:21 AM
  5. Replies: 1
    Last Post: 07-23-2007, 11:58 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •