Skip to content

Instantly share code, notes, and snippets.

@danielyaa5
Created March 8, 2016 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielyaa5/276e47ef93d8d4def81c to your computer and use it in GitHub Desktop.
Save danielyaa5/276e47ef93d8d4def81c to your computer and use it in GitHub Desktop.
private void connectToUrl() {
System.out.println("Connecting to requested server");
String[] requestLine = requestHeaders.get(0).split(" ");
String uri = requestLine[1];
String method = requestLine[0];
String domain = uri.substring(7, uri.length());
int index = domain.indexOf("/");
String hostname = domain.substring(0, index);
String directory = domain.substring(index, domain.length());
System.out.println("Method: " + method);
System.out.println("URI: " + uri);
System.out.println("Hostname: " + hostname);
System.out.println("Directory: " + directory);
System.out.println("Creating socket for " + hostname);
// start connection with the URL
Socket socket = null;
try {
socket = new Socket(hostname, 80);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Socket created successfully.");
// Send a request to the URL using PrintWriter
PrintWriter serv = null;
try {
serv = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Sending get request to: " + uri);
for (int i = 0; i < requestHeaders.size(); i++) {
serv.println(requestHeaders.get(i));
}
serv.println();
serv.flush();
// read from the URL into this stream
try {
is = socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = new byte[BUFFER];
int check = -1;
try {
check = is.read(data, 0, BUFFER);
} catch (IOException e) {
e.printStackTrace();
}
// while(check != -1) {
// // write the data back to the browser
// try {
// out.write(data, 0, check);
// check = is.read(data, 0, BUFFER);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment